Andrei Gabriel
Andrei Gabriel

Reputation: 25

React Query, useQuery returning undefined

Hello mighty developers,

I find myself in the following issue:

I have a hook called useMembers declared in a "util" file:

import { useQuery } from 'react-query';
import { customApi } from 'services/api';

export const useMembers = async ({ myId }) => {
  const {
    data: response, error, isError, isLoading,
  } = await useQuery(
    `endpoint-${myId}`,
    async () => {
      const bigMembers = await customApi.get(`one/lovely/endpoint`);
      return {
        ...bigMembers,
        data: {
          ...bigMembers.data,
          members: bigMembers.data,
        },
      };
    },
    {
      cacheTime: 0
    }
  );
  const memberList = response && response.data && response.data.members || []
    console.log(memberList) //return an array with 2 items;
  return {
    members: memberList,
    error,
    isError,
    isLoading,
    status: response?.status,
  };
};
export default useMembers;

In the Main Component file, I'm calling my hook but it gives undefined:

const {  members, error : errorOnMembers, isLoading: isLoadingOnMembers } = useMembers({ myId });
console.log({members}) //undefined;

I can't figure out why it gives undefined, should be an empty array at least

Upvotes: 0

Views: 9800

Answers (2)

Bearon
Bearon

Reputation: 21

You can try setting a variable in your fetch function that will store your data. Like this:

 const fetchAll = async () => {
    let fetchData;
    await axios.get(`/some/route/over/there`).then((res) => (fetchData = res.data));
    return fetchData;
  };

I'm using axios here but this should work with any http request. What's happening is there's a variable that react must check twice before rendering to page.

Upvotes: 0

trixn
trixn

Reputation: 16309

You can't await useQuery. React hooks are generally never async functions as they have to be called synchronously during render. Remove the async from useMembers and the await in front of useQuery.

Upvotes: 3

Related Questions