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
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.