React · Middle · Question 46 of 75
How do you implement an optimistic update via the cache in TanStack Query?
- ✓Correct answer:
onMutate- snapshot and edit the cache,onError- roll back - 2Call
invalidateQueriesat the very start of the mutation - 3Pass the
optimistic: trueoption to the list'suseQuery
Explanation
cancelQueries prevents a background request from overwriting the optimistic data. The snapshot from getQueryData is returned from onMutate as context for rollback. v5 has a simpler option - show the mutation's variables in the UI while it's isPending, without touching the cache.