I want to put swr
data into setState[]
I have code like this.
const { data } = useSWR('/api/data', fetcher);
const [contents, setcontents] = useState<Array<string>>([]);
How can I write code to put data
in setcontents[]
?
I want to put swr
data into setState[]
I have code like this.
const { data } = useSWR('/api/data', fetcher);
const [contents, setcontents] = useState<Array<string>>([]);
How can I write code to put data
in setcontents[]
?
You don’t need to do this. The data
is already part of the component’s state, and SWR is managing it for you. You don’t need to transfer the data into another state variable.
Use data
anywhere you were expecting to use contents
, and it will work as you expected. You can choose a different name for the variable if you like:
const { data: contents } = useSWR(...)
You can use useEffect hook to solve this problem.
useEffect(() => {
setcontents(data);
}, [data]);