How to set state with data coming from SWR? #2203
Unanswered
lvanoverberghe
asked this question in
Q&A
Replies: 1 comment 2 replies
-
hey @Lucasvo1, First of all there is no need have a state as same as data returned by Here's what you can do instead
But if you want to set state with data coming from SWR I guess you can do it in function Component() {
let [selectedXXX, setSelectedXXX] = useState({}) // you initial data
let { data } = useSWR('/api/xxx', fetcher, {
onSuccess: (data) => {
setSelectedXXX(() => data) // if request is finished successfully selectedXXX will get set to new data
}
})
} |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I use the following code, but the variable coming from SWR is undefined.
` const { data, error } = useSWR('/api/xxx', fetcher);
const [selectedXXX, setSelectedXXX] = useState(data.XXX[1])
//Handle the error state
if (error) return
//Handle the loading state
if (!data) return
`
Beta Was this translation helpful? Give feedback.
All reactions