Blog>
Snippets

Setting Up Dependent Queries with React Query

Demonstrate how to set up dependent queries that only run after certain conditions are met using React Query. This includes configuring a primary query that fetches a list of items and a dependent query that fetches detailed info for the first item, but only after the list query has successfully fetched data.
const { data: itemList } = useQuery(['itemsList'], fetchItemsList);
This line sets up the primary query to fetch a list of items. 'fetchItemsList' is a function that fetches the items list data. The useQuery hook is utilized with a unique key 'itemsList' to manage caching and re-fetching.
const firstItemId = itemList?.[0]?.id;
Extracts the ID of the first item from the fetched list. This ID will be used to fetch more detailed information in the dependent query.
const { data: firstItemDetails } = useQuery(['itemDetails', firstItemId], () => fetchItemDetails(firstItemId), { enabled: !!firstItemId });
Sets up a dependent query to fetch detailed information for the first item. This query only runs if 'firstItemId' is truthy, meaning the primary query completed successfully and there is a first item. 'fetchItemDetails' is a function that takes an item ID and returns the details for that item.