State
state/invalidate-after-mutation
After a mutation succeeds, invalidate or update every cached query it changed, so lists and details show the new data.
moderatemanualfe-data-fetching
Why
A cache does not know that the server changed. After "Add todo" succeeds, the list query still holds the old array until something refetches it, so the person sees their action "not work" and clicks again, creating a duplicate.
Fix
In onSuccess (or onSettled), call queryClient.invalidateQueries({ queryKey: ['todos'] }) with a key prefix that covers every affected list and detail; or write the returned entity into the cache with setQueryData when the response holds it. With SWR, call mutate(key). For instant feedback, use an optimistic update with a rollback in onError. Review every mutation for the queries it touches; key factories make the prefixes easy to find.
Examples
// bad
const add = useMutation({ mutationFn: addTodo })
// good
const add = useMutation({
mutationFn: addTodo,
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
})Sources
Facts
- Id
state/invalidate-after-mutation- Severity
- moderate
- Check
- manual a person reviews it; the report lists it as a checklist
- Applies to
jsxvuesvelteangular- Only in projects with
tanstack-queryswr- Taught by the skill
fe-data-fetchingData fetching- Since version
- 0.1.0
Read it in the terminal
npx github:dawidolko/frontend-skills explain state/invalidate-after-mutation