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(): Promise<Todos> {
24 const response = await fetch('/api/data')
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: string) => {
49 setText('')
50 // Cancel any outgoing refetch
51 // (so they don't overwrite our optimistic update)
52 await queryClient.cancelQueries(todoListOptions)
53β
54 // Snapshot the previous value
55 const previousTodos = queryClient.getQueryData(todoListOptions.queryKey)
56β
57 // Optimistically update to the new value
58 if (previousTodos) {
59 queryClient.setQueryData(todoListOptions.queryKey, {
60 ...previousTodos,
61 items: [
62 ...previousTodos.items,
63 { id: Math.random().toString(), text: newTodo },
64 ],
65 })
66 }
67β
68 return { previousTodos }
69 },
70 // If the mutation fails,
71 // use the context returned from onMutate to roll back
72 onError: (err, variables, context) => {
73 if (context?.previousTodos) {
74 queryClient.setQueryData<Todos>(['todos'], context.previousTodos)
75 }
76 },
77 // Always refetch after error or success:
78 onSettled: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
79 })
80β
81 return (
82 <div>
83 <p>
84 In this example, new items can be created using a mutation. The new item
85 will be optimistically added to the list in hopes that the server
86 accepts the item. If it does, the list is refetched with the true items
87 from the list. Every now and then, the mutation may fail though. When
88 that happens, the previous list of items is restored and the list is
89 again refetched from the server.
90 </p>
91 <form
92 onSubmit={(e) => {
93 e.preventDefault()
94 addTodoMutation.mutate(text)
95 }}
96 >
97 <input
98 type="text"
99 onChange={(event) => setText(event.target.value)}
100 value={text}
101 />
102 <button disabled={addTodoMutation.isPending}>Create</button>
103 </form>
104 <br />
105 {queryInfo.isSuccess && (
106 <>
107 <div>
108 {/* The type of queryInfo.data will be narrowed because we check for isSuccess first */}
109 Updated At: {new Date(queryInfo.data.ts).toLocaleTimeString()}
110 </div>
111 <ul>
112 {queryInfo.data.items.map((todo) => (
113 <li key={todo.id}>{todo.text}</li>
114 ))}
115 </ul>
116 {isFetching && <div>Updating in background...</div>}
117 </>
118 )}
119 {queryInfo.isLoading && 'Loading'}
120 {queryInfo.error instanceof Error && queryInfo.error.message}
121 </div>
122 )
123}
124β
125export default function App() {
126 return (
127 <QueryClientProvider client={client}>
128 <Example />
129 <ReactQueryDevtools initialIsOpen />
130 </QueryClientProvider>
131 )
132}