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