In React Query, you can use dependent queries to fetch data that relies on the result of a previous query. This is useful when you need to wait for one piece of data before making another request. Here's how you can implement dependent queries using the useQuery hook.
Example Scenario
Let's say you have a user ID, and you want to fetch user details first, and then based on those details, you want to fetch the user's posts.
Step-by-Step Implementation
Install React Query: If you haven't already, install React Query in your project.
npm install @tanstack/react-query
Set Up Query Client: Wrap your application with the QueryClientProvider.
import React from 'react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import App from './App';
const queryClient = new QueryClient();
const Root = () => (
<QueryClientProvider client={queryClient}>
<App />
</QueryClientProvider>
);
export default Root;
Create Dependent Queries: Use the useQuery hook to fetch data. The second query will depend on the result of the first query.
import React from 'react';
import { useQuery } from '@tanstack/react-query';
const fetchUser = async (userId) => {
const response = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`);
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
};
const fetchUserPosts = async (userId) => {
const response = await fetch(`https://jsonplaceholder.typicode.com/posts?userId=${userId}`);
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
};
const UserProfile = ({ userId }) => {
// First query to fetch user details
const { data: user, error: userError, isLoading: isUserLoading } = useQuery(['user', userId], () => fetchUser(userId));
// Second query to fetch user posts, which depends on the userId
const { data: posts, error: postsError, isLoading: isPostsLoading } = useQuery(
['posts', userId],
() => fetchUserPosts(userId),
{
enabled: !!userId, // Only run this query if userId is truthy
}
);
if (isUserLoading) return <div>Loading user...</div>;
if (userError) return <div>Error loading user: {userError.message}</div>;
if (isPostsLoading) return <div>Loading posts...</div>;
if (postsError) return <div>Error loading posts: {postsError.message}</div>;
return (
<div>
<h1>{user.name}</h1>
<h2>Posts:</h2>
<ul>
{posts.map((post) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</div>
);
};
export default UserProfile;
Explanation
First Query: The first useQuery fetches user details based on the userId. It uses a unique query key ['user', userId] to identify the query.
Second Query: The second useQuery fetches posts for the user. It also uses a unique query key ['posts', userId]. The enabled option is set to !!userId, which means this query will only run if userId is truthy (i.e., not null or undefined).
Loading and Error States: Both queries handle loading and error states, providing feedback to the user.
Conclusion
Using dependent queries in React Query is straightforward. By leveraging the enabled option, you can control when a query should run based on the results of another query. This pattern is very useful for scenarios where data dependencies exist.