0

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

3
  • can you try to return response and check if the data is correct on response.data.members? Commented Mar 25, 2021 at 11:11
  • 1
    why are you awaiting useQuery? It does not return a Promise. Commented Mar 25, 2021 at 11:14
  • @trixn . Thank you! It fixed the problem, give it as an official answer so I can accept it. Commented Mar 25, 2021 at 11:26

2 Answers 2

3

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.

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

Comments

0

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.

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.