Open History to see the last commit
1import * as React from 'react'
2β
3import {
4 QueryClient,
5 QueryClientProvider,
6 queryOptions,
7 useMutation,
8 useQuery,
9 useQueryClient,
10} from '@tanstack/react-query'
11import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
12β
13const client = new QueryClient()
14β
15type Todos = {
16 items: ReadonlyArray<{
17 id: string
18 text: string
19 }>
20 ts: number
21}
22β
23async function fetchTodos({ signal }: { signal: AbortSignal }): Promise<Todos> {
24 const response = await fetch('/api/data', { signal })
25 return await response.json()
26}
27β
28const todoListOptions = queryOptions({
29 queryKey: ['todos'],
30 queryFn: fetchTodos,
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
91 will be optimistically added to the list in hopes that the server
92 accepts the item. If it does, the list is refetched with the true items
93 from the list. Every now and then, the mutation may fail though. When
94 that happens, the previous list of items is restored and the list is
95 again refetched from the server.
96 </p>
97 <form
98 onSubmit={(e) => {
99 e.preventDefault()
100 addTodoMutation.mutate(text)
101 }}
102 >
103 <input
104 type="text"
105 onChange={(event) => setText(event.target.value)}
106 value={text}
107 />
108 <button disabled={addTodoMutation.isPending}>Create</button>
109 </form>
110 <br />
111 {queryInfo.isSuccess && (
112 <>
113 <div>
114 {/* The type of queryInfo.data will be narrowed because we check for isSuccess first */}
115 Updated At: {new Date(queryInfo.data.ts).toLocaleTimeString()}
116 </div>
117 <ul>
118 {queryInfo.data.items.map((todo) => (
119 <li key={todo.id}>{todo.text}</li>
120 ))}
121 </ul>
122 {isFetching && <div>Updating in background...</div>}
123 </>
124 )}
125 {queryInfo.isLoading && 'Loading'}
126 {queryInfo.error instanceof Error && queryInfo.error.message}
127 </div>
128 )
129}
130β
131export default function App() {
132 return (
133 <QueryClientProvider client={client}>
134 <Example />
135 <ReactQueryDevtools initialIsOpen />
136 </QueryClientProvider>
137 )
138}