skip to Main Content

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


  1. 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.

    const { data: response, refetch } = useQuery({
        queryKey: ['get-response'],
        queryFn: async() => {
            return await Axios.get('URL').then((res) => res.data);
        },
        onSuccess(response) {
            console.log(response); // logs the response
            anotherFunctionThatWillUseResponse(response);
        },
        enabled: false, //to allow refetch() onClick
    });
    
    const onSubmit = async () => {
        await refetch();
    };
    
    Login or Signup to reply.
  2. because the data is still loading if you add isloading like this

    const { data: response, refetch , islLoading } 
    

    and replace

        console.log(response) // logs undefined 
    

    with

      console.log(islLoading ) // you will get true
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search