Stan aplikacji
state/invalidate-after-mutation
After a mutation succeeds, invalidate or update every cached query it changed, so lists and details show the new data.
umiarkowanaręcznefe-data-fetching
Dlaczego
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.
Poprawka
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.
Przykłady
// bad
const add = useMutation({ mutationFn: addTodo })
// good
const add = useMutation({
mutationFn: addTodo,
onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
})Źródła
Fakty
- Identyfikator
state/invalidate-after-mutation- Waga
- umiarkowana
- Sprawdzanie
- ręczne ocenia człowiek; raport podaje to jako listę kontrolną
- Dotyczy plików
jsxvuesvelteangular- Tylko w projektach z
tanstack-queryswr- Uczy jej skill
fe-data-fetchingData fetching- Od wersji
- 0.1.0
Przeczytaj w terminalu
npx github:dawidolko/frontend-skills explain state/invalidate-after-mutation