Skip to content

Pattern for fetching a list and mutating a single item within the list #5037

Answered by TkDodo
matomesc asked this question in Q&A
Discussion options

You must be logged in to vote

which will cause the entire list to be refetched. Is there a pattern that prevents having to refetch the entire list? This seems like a common use case but I haven't been able to figure it out.

your query always fetches from /api/posts, so an invalidation will always refetch the entire list. That's often a good thing - items could have been added or altered by someone else in the meantime, so now you'd have the up-to-date data.

If you don't want that, have a look at Updates from Mutation Responses. If your mutation returns the updated item, you can write it back to the list in onSuccess:

onSuccess: (item) => {
  queryClient.setQueryData(
    ['posts'],
    (prev) => prev?.map(post => po…

Replies: 2 comments 3 replies

Comment options

You must be logged in to vote
2 replies
@matomesc
Comment options

@radik-albaik
Comment options

Answer selected by matomesc
Comment options

You must be logged in to vote
1 reply
@bfaulk96
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
5 participants