3

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
   // });
3
  • What is the shape of the API response? Commented Apr 19, 2022 at 17:39
  • It is an object. Looks like this {name: string, date: date, champion: array, deadlines: array} Commented Apr 19, 2022 at 17:48
  • So the object doesn't have a data property? Then why are you trying to return the data property from it in getEventById. I think you just need to return data. Then your useQuery would look like: const { isLoading, data, error } = useQuery('conf_id', getEventById}); And you can access those values via data.name or data.deadlines, etc. Commented Apr 19, 2022 at 19:21

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.