There are two ways to handle multiple queries with React Query.
Method 1: Call useQuery Twice
The simplest method is just to call useQuery twice but re-assign the data variable that we're destructuring. They can't both be called data.
const { data: userData } = useQuery("users", fetchUsers);
const { data: postData } = useQuery("posts", fetchPosts);
Method 2: useQueries
There is also useQueries
which is perfect for this situation. It returns an array of queries. We can get access to each one using array destructuring.
const [posts, users] = useQueries([
{ queryKey: ["posts"], queryFn: fetchPosts },
{ queryKey: ["users"], queryFn: fetchUsers }
]);
The queries that are returned from useQueries
also contains the usual suspects like isLoading
isError
etc.
const [posts, users] = useQueries([
{ queryKey: ["posts"], queryFn: fetchPosts },
{ queryKey: ["users"], queryFn: fetchUsers }
]);
const { data, isLoading } = posts;
There are also situations where you may want to wait for everything to finish before rendering any data. In that case, we can check if any / some of the queries are still in their loading state (isLoading
comes from the useQuery
hook).
const results = useQueries([
{ queryKey: ["posts"], queryFn: fetchPosts },
{ queryKey: ["users"], queryFn: fetchUsers }
]);
const isLoading = results.some((query) => query.isLoading);
return { isLoading, results };
Within our component, we only need to pull in 1 isLoading
value and handle that case until ALL of the results are ready.
Top comments (0)