Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

useQuery always returning undefined data in react-query

I'm new to react-query and I'm trying to move all of my API calls into a new file, out of the useQuery calls. Unfortunately when I do this all of my data is undefined.

I do see the network calls in the network tab, it just isn't being set properly in useQuery.

Thanks in advance for any help on how to change my code to fix this!

   // this works
    const { loading, data, error } = useQuery([conf_id], async () => {
       const { data } = await axios.get(API_URL + '/event/' + conf_id)
       return data
    });
    // this doesn't work - data is undefined
    const axios = require('axios');
    
    const getEventById = async () => {
      const { data } = await axios.get(API_URL + '/event/2541' + '?noyear=true');
      return data.data;
    };
    
    const { loading, data, error } = useQuery('conf_id', getEventById});
    // the below variants don't work either
    // const { loading, data, error } = useQuery('conf_id', getEventById()});
    // const { loading, data, error } = useQuery('conf_id', async () => await getEventById()});
   // const { loading, data, error } = useQuery('conf_id', async () => await 
   //    const { data } = getEventById(); return data
   // });
like image 917
Mcestone Avatar asked Aug 20 '26 01:08

Mcestone


1 Answers

An AxiosResponse has a data attribute from which you can access the actual API JSON response.

Like you pointed out, this:

async () => {
       const { data } = await axios.get(API_URL + '/event/' + conf_id)
       return data
    }

Should suffice for the fetching function.

So the final implementation should look like


    const axios = require('axios');
    
    const getEventById = async () => {
      const { data } = await axios.get(API_URL + '/event/2541' + '?noyear=true');
      return data;
    };
    
    const { loading, data, error } = useQuery('conf_id', getEventById);

The data you get from the useQuery should be undefined on the first render and once the server responds it will change to whatever the response is.

like image 174
Gerardo Sabetta Avatar answered Aug 21 '26 16:08

Gerardo Sabetta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!