MCPcopy
hub / github.com/TanStack/query / Example

Function Example

examples/react/optimistic-updates-cache/src/pages/index.tsx:33–129  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

31})
32
33function Example() {
34 const queryClient = useQueryClient()
35 const [text, setText] = React.useState('')
36 const { isFetching, ...queryInfo } = useQuery(todoListOptions)
37
38 const addTodoMutation = useMutation({
39 mutationFn: async (newTodo: string) => {
40 const response = await fetch('/api/data', {
41 method: 'POST',
42 body: JSON.stringify({ text: newTodo }),
43 headers: { 'Content-Type': 'application/json' },
44 })
45 return await response.json()
46 },
47 // When mutate is called:
48 onMutate: async (newTodo, context) => {
49 setText('')
50 // Cancel any outgoing refetch
51 // (so they don't overwrite our optimistic update)
52 await context.client.cancelQueries(todoListOptions)
53
54 // Snapshot the previous value
55 const previousTodos = context.client.getQueryData(
56 todoListOptions.queryKey,
57 )
58
59 // Optimistically update to the new value
60 if (previousTodos) {
61 context.client.setQueryData(todoListOptions.queryKey, {
62 ...previousTodos,
63 items: [
64 ...previousTodos.items,
65 { id: Math.random().toString(), text: newTodo },
66 ],
67 })
68 }
69
70 return { previousTodos }
71 },
72 // If the mutation fails,
73 // use the result returned from onMutate to roll back
74 onError: (err, variables, onMutateResult, context) => {
75 if (onMutateResult?.previousTodos) {
76 context.client.setQueryData<Todos>(
77 ['todos'],
78 onMutateResult.previousTodos,
79 )
80 }
81 },
82 // Always refetch after error or success:
83 onSettled: (data, error, variables, onMutateResult, context) =>
84 context.client.invalidateQueries({ queryKey: ['todos'] }),
85 })
86
87 return (
88 <div>
89 <p>
90 In this example, new items can be created using a mutation. The new item

Callers

nothing calls this directly

Calls 9

useQueryClientFunction · 0.90
useQueryFunction · 0.90
useMutationFunction · 0.90
toStringMethod · 0.80
cancelQueriesMethod · 0.45
getQueryDataMethod · 0.45
setQueryDataMethod · 0.45
invalidateQueriesMethod · 0.45
mutateMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…