3

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[] ?

minsu
  • 121
  • 1
  • 1
  • 8

2 Answers2

3

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(...)
Stephen Jennings
  • 12,494
  • 5
  • 47
  • 66
0

You can use useEffect hook to solve this problem.

useEffect(() => {
    setcontents(data);
  }, [data]);
Viral Patel
  • 1,104
  • 4
  • 7