T
TanStack•3y ago
plain-purple

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,
});
// 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);
// 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')
},
});
// 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.
2 Replies
adverse-sapphire
adverse-sapphire•3y ago
I'd do the invalidation
plain-purple
plain-purpleOP•3y ago
Thanks for the response, @TkDodo 🔮 ! We've used your articles as reference frequently, they're very well done.

Did you find this page helpful?