Blog>
Snippets

Dependent Queries in React Query

Illustrate how to manage dependent queries, where the result of one query depends on the successful completion of another, using React Query's useQuery hook.
import { useQuery } from 'react-query';
import axios from 'axios';

const fetchUserByEmail = async (email) => {
  const { data } = await axios.get(`/api/users/${email}`);
  return data;
};

const fetchProjectsByUserId = async (userId) => {
  const { data } = await axios.get(`/api/projects/${userId}`);
  return data;
};
Defines two asynchronous functions using axios to fetch data. The first function fetches a user by email and the second function fetches projects by a given user's ID.
const UserDetails = ({ email }) => {
  // First query to fetch user by email
  const { data: user, isSuccess } = useQuery(['user', email], () => fetchUserByEmail(email), {
    enabled: !!email // This query won't run until the email is provided
  });

  // Dependent query to fetch projects once the user has been successfully fetched
  const { data: projects } = useQuery(['projects', user?.id], () => fetchProjectsByUserId(user.id), {
    enabled: !!user?.id // This query depends on the userId from the first query
  });

  return (
    <div>
      {/* Render user and projects data */}
    </div>
  );
};
Creates a React component, UserDetails, that demonstrates dependent querying. It uses the useQuery hook twice: the first query fetches user details by email, and the second query fetches the user's projects, which depends on the successful completion of the first query.