So, I’m trying to fetch data -onClick- using reactQuery and to store the response in a variable.
const { data: response, refetch } = useQuery({
queryKey: ['get-response'],
queryFn: async() => {
return await Axios.get('URL').then((res) => res.data);
},
enabled: false, //to allow refetch() onClick
});
const onSubmit = async () => {
await refetch();
console.log(response) // logs undefined
anotherFunctionThatWillUseResponse(response)
};
//if I console.log(response) here it will later show the response
I know I can use useEffect
to listen on the response and do whatever inside of the useEffect, but I’m wondering why it returns undefined first, and how to properly handle this behavior
2
Answers
That is the expected behavior. When you call refetch function, it re-renders the component, but runs the onSubmit function before that. So the states are the same (old). To fix this, use
onSuccess
handler with useQuery hook.because the data is still loading if you add isloading like this
and replace
with