Open History to see the last commit
1---
2id: optimistic-updates
3title: Optimistic Updates
4ref: docs/framework/react/guides/optimistic-updates.md
5replace:
6 { 'React': 'Svelte', 'useMutation': 'createMutation', 'hook': 'function' }
7---
8β
9[//]: # 'ExampleUI1'
10β
11```ts
12const addTodoMutation = createMutation(() => ({
13 mutationFn: (newTodo: string) => axios.post('/api/data', { text: newTodo }),
14 // make sure to _return_ the Promise from the query invalidation
15 // so that the mutation stays in `pending` state until the refetch is finished
16 onSettled: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
17}))
18```
19β
20[//]: # 'ExampleUI1'
21[//]: # 'ExampleUI2'
22β
23```svelte
24<ul>
25 {#each todoQuery.data as todo}
26 <li>{todo.text}</li>
27 {/each}
28 {#if addTodoMutation.isPending}
29 <li style:opacity="0.5">{addTodoMutation.variables}</li>
30 {/if}
31</ul>
32```
33β
34[//]: # 'ExampleUI2'
35[//]: # 'ExampleUI3'
36β
37```svelte
38{#if addTodoMutation.isError}
39 <li style:color="red">
40 {addTodoMutation.variables}
41 <button onclick={() => addTodoMutation.mutate(addTodoMutation.variables)}>
42 Retry
43 </button>
44 </li>
45{/if}
46```
47β
48[//]: # 'ExampleUI3'
49[//]: # 'ExampleUI4'
50β
51```ts
52// somewhere in your app
53const mutation = createMutation(() => ({
54 mutationFn: (newTodo: string) => axios.post('/api/data', { text: newTodo }),
55 onSettled: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
56 mutationKey: ['addTodo'],
57}))
58β
59// access variables somewhere else
60const variables = useMutationState({
61 filters: { mutationKey: ['addTodo'], status: 'pending' },
62 select: (mutation) => mutation.state.variables,
63})
64```
65β
66[//]: # 'ExampleUI4'
67[//]: # 'Example'
68β
69```ts
70const queryClient = useQueryClient()
71β
72createMutation(() => ({
73 mutationFn: updateTodo,
74 // When mutate is called:
75 onMutate: async (newTodo, context) => {
76 // Cancel any outgoing refetches
77 // (so they don't overwrite our optimistic update)
78 await context.client.cancelQueries({ queryKey: ['todos'] })
79β
80 // Snapshot the previous value
81 const previousTodos = context.client.getQueryData(['todos'])
82β
83 // Optimistically update to the new value
84 context.client.setQueryData(['todos'], (old) => [...(old ?? []), newTodo])
85β
86 // Return a result with the snapshotted value
87 return { previousTodos }
88 },
89 // If the mutation fails,
90 // use the result returned from onMutate to roll back
91 onError: (err, newTodo, onMutateResult, context) => {
92 context.client.setQueryData(['todos'], onMutateResult.previousTodos)
93 },
94 // Always refetch after error or success:
95 onSettled: (data, error, variables, onMutateResult, context) =>
96 context.client.invalidateQueries({ queryKey: ['todos'] }),
97}))
98```
99β
100[//]: # 'Example'
101[//]: # 'Example2'
102β
103```ts
104createMutation(() => ({
105 mutationFn: updateTodo,
106 // When mutate is called:
107 onMutate: async (newTodo, context) => {
108 // Cancel any outgoing refetches
109 // (so they don't overwrite our optimistic update)
110 await context.client.cancelQueries({ queryKey: ['todos', newTodo.id] })
111β
112 // Snapshot the previous value
113 const previousTodo = context.client.getQueryData(['todos', newTodo.id])
114β
115 // Optimistically update to the new value
116 context.client.setQueryData(['todos', newTodo.id], newTodo)
117β
118 // Return a result with the previous and new todo
119 return { previousTodo, newTodo }
120 },
121 // If the mutation fails, use the result we returned above
122 onError: (err, newTodo, onMutateResult, context) => {
123 context.client.setQueryData(
124 ['todos', onMutateResult?.newTodo.id],
125 onMutateResult?.previousTodo,
126 )
127 },
128 // Always refetch after error or success:
129 onSettled: (newTodo, error, variables, onMutateResult, context) =>
130 context.client.invalidateQueries({ queryKey: ['todos', variables.id] }),
131}))
132```
133β
134[//]: # 'Example2'
135[//]: # 'Example3'
136β
137```ts
138createMutation(() => ({
139 mutationFn: updateTodo,
140 // ...
141 onSettled: async (newTodo, error, variables, onMutateResult, context) => {
142 if (error) {
143 // do something
144 }
145 },
146}))
147```
148β
149[//]: # 'Example3'