Open History to see the last commit
1---
2id: invalidations-from-mutations
3title: Invalidations from Mutations
4---
5β
6Invalidating queries is only half the battle. Knowing **when** to invalidate them is the other half. Usually when a mutation in your app succeeds, it's VERY likely that there are related queries in your application that need to be invalidated and possibly refetched to account for the new changes from your mutation.
7β
8For example, assume we have a mutation to post a new todo:
9β
10[//]: # 'Example'
11β
12```tsx
13const mutation = useMutation({ mutationFn: postTodo })
14```
15β
16[//]: # 'Example'
17β
18When a successful `postTodo` mutation happens, we likely want all `todos` queries to get invalidated and possibly refetched to show the new todo item. To do this, you can use `useMutation`'s `onSuccess` options and the `client`'s `invalidateQueries` function:
19β
20[//]: # 'Example2'
21β
22```tsx
23import { useMutation, useQueryClient } from '@tanstack/react-query'
24β
25const queryClient = useQueryClient()
26β
27// When this mutation succeeds, invalidate any queries with the `todos` or `reminders` query key
28const mutation = useMutation({
29 mutationFn: addTodo,
30 onSuccess: async () => {
31 // If you're invalidating a single query
32 await queryClient.invalidateQueries({ queryKey: ['todos'] })
33β
34 // If you're invalidating multiple queries
35 await Promise.all([
36 queryClient.invalidateQueries({ queryKey: ['todos'] }),
37 queryClient.invalidateQueries({ queryKey: ['reminders'] }),
38 ])
39 },
40})
41```
42β
43[//]: # 'Example2'
44β
45Returning a Promise on `onSuccess` makes sure the data is updated before the mutation is entirely complete (i.e., isPending is true until onSuccess is fulfilled)
46β
47[//]: # 'Example2'
48β
49You can wire up your invalidations to happen using any of the callbacks available in the [`useMutation` hook](./mutations.md)
50β
51[//]: # 'Materials'
52β
53## Further reading
54β
55For a technique to automatically invalidate Queries after Mutations, have a look at [TkDodo's article on Automatic Query Invalidation after Mutations](https://tkdodo.eu/blog/automatic-query-invalidation-after-mutations).
56β
57[//]: # 'Materials'