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: () => {
79 queryClient.invalidateQueries({ queryKey: ['todos'] })
80 },
81 })
82β
83 return (
84 <div>
85 <p>
86 In this example, new items can be created using a mutation. The new item
87 will be optimistically added to the list in hopes that the server
88 accepts the item. If it does, the list is refetched with the true items
89 from the list. Every now and then, the mutation may fail though. When
90 that happens, the previous list of items is restored and the list is
91 again refetched from the server.
92 </p>
93 <form
94 onSubmit={(e) => {
95 e.preventDefault()
96 addTodoMutation.mutate(text)
97 }}
98 >
99 <input
100 type="text"
101 onChange={(event) => setText(event.target.value)}
102 value={text}
103 />
104 <button disabled={addTodoMutation.isPending}>Create</button>
105 </form>
106 <br />
107 {queryInfo.isSuccess && (
108 <>
109 <div>
110 {/* The type of queryInfo.data will be narrowed because we check for isSuccess first */}
111 Updated At: {new Date(queryInfo.data.ts).toLocaleTimeString()}
112 </div>
113 <ul>
114 {queryInfo.data.items.map((todo) => (
115 <li key={todo.id}>{todo.text}</li>
116 ))}
117 </ul>
118 {isFetching && <div>Updating in background...</div>}
119 </>
120 )}
121 {queryInfo.isLoading && 'Loading'}
122 {queryInfo.error instanceof Error && queryInfo.error.message}
123 </div>
124 )
125}
126β
127export default function App() {
128 return (
129 <QueryClientProvider client={client}>
130 <Example />
131 <ReactQueryDevtools initialIsOpen />
132 </QueryClientProvider>
133 )
134}