Fetching dependent queries with useQuery
Sometimes, during our development process, we need to have values that are returned from one query that we can use in another query or have a query execution depend on a previous query. When this happens, we need to have what is called a dependent query.
React Query allows you to make a query depend on others via the enabled option.
This is how you can do it:
const App = () => {
const { data: firstQueryData } = useQuery({
queryKey: ["api"],
queryFn: fetchData,
});
const canThisDependentQueryFetch = firstQueryData?.hello
!== undefined;
const { data: dependentData } = useQuery({
queryKey: ["dependentApi", firstQueryData?.hello],
queryFn: fetchDependentData,
enabled: canThisDependentQueryFetch,
});
…
In...