TanStackT
TanStack3y ago
3 replies
near-sapphire

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,
  });


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]);
    },
  });


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!
Was this page helpful?