TanStackT
TanStack3y ago
2 replies
specific-silver

Dependent query best-practices

We're curious if there is a preferred method of invalidating dependent queries, as my coworker and I took two different approaches based on our understanding of the documentation.

We have two queries both wrapped in hooks, one called
favorites
and the other
offers
. The
favorites
data is an array of items the user can add or remove from, whereas the
offers
data is generated by the backend based on the items the user adds to their
favorites
.

The desired functionality is that when a user adds or removes a
favorite
, the
offers
data is refetched.

One approach was to add the
favorites.data
property as a dependency of the
offers
query key, with the understanding that if
favorites.data
changed, the
offers
query would refetch.
// userOffers.tsx
const {favoritesQuery} = useFavorites();
const offersQuery = useQuery(['offers', favoritesQuery.data], getOffers, {
    enabled:  !!favoritesQuery.data,
});

The other approach was to invalidate the dependent query from the
onSuccess
handler of the mutation functions in the
favorites
hook.
// useOffers.tsx
const offersQuery = useQuery(['offers'], getOffers);

// useFavorites.tsx
const addFavorite = useMutation({
    mutationFn: (favorite) =>  addFavorite(favorite),
    onMutate: () => {// Optimistic updating}
    onSuccess: () => {
        //...
        queryClient.invalidateQueries('offers')
    },
});
const removeFavorite = useMutation({
    //...
    onSuccess: () => {
        //...
        queryClient.invalidateQueries('offers')
    },
});

Is either approach more consistent with the React Query paradigm? Is there another route we may both be overlooking? Any help is appreciated.
Was this page helpful?