Open History to see the last commit
1import * as React from 'react'
2import axios from 'axios'
3β
4import {
5 useQuery,
6 useQueryClient,
7 useMutation,
8 QueryClient,
9 QueryClientProvider,
10} from '@tanstack/react-query'
11import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
12β
13const client = new QueryClient()
14β
15type Todos = {
16 items: readonly {
17 id: string
18 text: string
19 }[]
20 ts: number
21}
22β
23async function fetchTodos(): Promise<Todos> {
24 const res = await axios.get('/api/data')
25 return res.data
26}
27β
28function useTodos() {
29 return useQuery({ queryKey: ['todos'], queryFn: fetchTodos })
30}
31β
32function Example() {
33 const queryClient = useQueryClient()
34 const [text, setText] = React.useState('')
35 const todoQuery = useTodos()
36β
37 const addTodoMutation = useMutation({
38 mutationFn: (newTodo: string) => axios.post('/api/data', { text: newTodo }),
39 onSettled: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
40 })
41β
42 return (
43 <div>
44 <p>
45 In this example, new items can be created using a mutation. The new item
46 will be optimistically added to the list in hopes that the server
47 accepts the item. If it does, the list is refetched with the true items
48 from the list. Every now and then, the mutation may fail though. When
49 that happens, the previous list of items is restored and the list is
50 again refetched from the server.
51 </p>
52 <form
53 onSubmit={(e) => {
54 e.preventDefault()
55 setText('')
56 addTodoMutation.mutate(text)
57 }}
58 >
59 <input
60 type="text"
61 onChange={(event) => setText(event.target.value)}
62 value={text}
63 />
64 <button disabled={addTodoMutation.isPending}>Create</button>
65 </form>
66 <br />
67 {todoQuery.isSuccess && (
68 <>
69 <div>
70 {/* The type of queryInfo.data will be narrowed because we check for isSuccess first */}
71 Updated At: {new Date(todoQuery.data.ts).toLocaleTimeString()}
72 </div>
73 <ul>
74 {todoQuery.data.items.map((todo) => (
75 <li key={todo.id}>{todo.text}</li>
76 ))}
77 {addTodoMutation.isPending && (
78 <li style={{ opacity: 0.5 }}>{addTodoMutation.variables}</li>
79 )}
80 {addTodoMutation.isError && (
81 <li style={{ color: 'red' }}>
82 {addTodoMutation.variables}
83 <button
84 onClick={() =>
85 addTodoMutation.mutate(addTodoMutation.variables)
86 }
87 >
88 Retry
89 </button>
90 </li>
91 )}
92 </ul>
93 {todoQuery.isFetching && <div>Updating in background...</div>}
94 </>
95 )}
96 {todoQuery.isPending && 'Loading'}
97 {todoQuery.error instanceof Error && todoQuery.error.message}
98 </div>
99 )
100}
101β
102export default function App() {
103 return (
104 <QueryClientProvider client={client}>
105 <Example />
106 <ReactQueryDevtools initialIsOpen />
107 </QueryClientProvider>
108 )
109}