Mcestone
Mcestone

Reputation: 864

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
   // });

Upvotes: 3

Views: 18280

Answers (1)

Gerardo Sabetta
Gerardo Sabetta

Reputation: 559

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.

Upvotes: 2

Related Questions