T
TanStack3y ago
genetic-orange

Understanding Query Keys

Good day, people! I need help in understanding query keys in general for invalidation and caching. I have a query that fetches all the posts for your timeline in a social media app. A Post has {poster, comments, likes, postId}
const query = useQuery({
queryKey: ['posts'],
queryFn: getAllPosts,
});
const query = useQuery({
queryKey: ['posts'],
queryFn: getAllPosts,
});
Now, in another component, I wanted to make a patch request to update the likes and invalidate the current post only and not the whole fetched posts. If I don't include the post.id props in the invalidateQueries, it works as intended but that means it will invalidate all of the fetched posts (correct me if I'm wrong).
const likeMutation = useMutation({
mutationFn: updatePostLike,
onSuccess: () => {
queryClient.invalidateQueries(['posts', post.id]);
},
});
const likeMutation = useMutation({
mutationFn: updatePostLike,
onSuccess: () => {
queryClient.invalidateQueries(['posts', post.id]);
},
});
How should I update my useQuery or mutation function so that I can include the postIds in the queryKey? or is there another solution for this? Thank you for your help!
3 Replies
harsh-harlequin
harsh-harlequin3y ago
basically you need to invalidate both queries. The query that fetched the list of posts (as one of the posts in the list has changed thus the list is "invalid" now) and if you have a query to fetch an individual post, you have to invalidate that query as well (that's what you already have in your onSuccess callback. So you would need to add the the callback: `queryClient.invalidateQueries(['posts']); as well. There is no way to just invalidate a single item within a list of items, that were returned from a query. The only other thing you could do is to update the results of the posts-query with the updated data from the mutation - look at https://tanstack.com/query/latest/docs/react/guides/updates-from-mutation-responses
Updates from Mutation Responses | TanStack Query Docs
When dealing with mutations that update objects on the server, it's common for the new object to be automatically returned in the response of the mutation. Instead of refetching any queries for that item and wasting a network call for data we already have, we can take advantage of the object returned by the mutation function and update the exis...
genetic-orange
genetic-orangeOP3y ago
Sorry for the late reply, eiben. I appreciate your response! I see, I assumed invalidating the whole fetched posts is wrong. I understand it now. I will read about that setQueryData. Thank you so much!
harsh-harlequin
harsh-harlequin3y ago
Well, you're right as you will always have to invalidate the whole list of posts when you update an individual post and have to refetch this list in consequent.

Did you find this page helpful?