0

I'm trying to render a loading component while my queries are being executed in parallel in react-query.

I'm looping through an array of ids and making the same request.

const useGetUsersQueries = (
  users
) => {
  const queries = useQueries({
    queries: users?.map((user) => ({
      queryKey: ['get-users-query', user.id],
      queryFn: async (): Promise<RoutineData> => {
        const response = await getUsers(
          user.id,
        );
        return response.data;
      },
      enabled: !!user
    }))
  });

  const isLoading = queries.some((query) => query.isLoading);
  const isSuccess = queries.every((query) => query.isSuccess);
  const isError = queries.some((query) => query.isError);
 
  const data = queries.filter((query) => query.data)

  return [data, { isLoading, isSuccess, isError }];
};

In my component I'm trying to render a loading component while the query is being fetched, but for each user.

const [usersData, {isLoading}] = useGetUsersQueries(users);

{usersData.map((query, index) => {
   return (
      <>
         {query.isLoading && (<Loading />)}  // this loading is always false
         {query.isSuccess && (<Component />)} // this success is always true          
      </>
   );
 })}

Is it possible to get the loading state for each user that is being fetched? Or its only possible to get a loading state for all the queries at once?

1

1 Answer 1

0

The useQueries hook returns an array with all the query results. The order returned is the same as the input order.

Use another variable in your filter function to get the isLoading prop for every user similar to getting the data prop.

const loadingData = queries.filter((query) => query.isLoading)

or club them together in a single data structure and use them in your components.

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.