Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

index.tsx

128 lines3.5 KB

1import * as React from 'react'
2import axios from 'axios'
3​
4import {
5 queryOptions,
6 useQuery,
7 useQueryClient,
8 useMutation,
9 QueryClient,
10 QueryClientProvider,
11} from '@tanstack/react-query'
12import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
13​
14const client = new QueryClient()
15​
16type Todos = {
17 items: readonly {
18 id: string
19 text: string
20 }[]
21 ts: number
23​
24async function fetchTodos(): Promise<Todos> {
25 const res = await axios.get('/api/data')
26 return res.data
28​
29const todoListOptions = queryOptions({
30 queryKey: ['todos'],
31 queryFn: fetchTodos,
32})
33​
34function Example() {
35 const queryClient = useQueryClient()
36 const [text, setText] = React.useState('')
37 const { isFetching, ...queryInfo } = useQuery(todoListOptions)
38​
39 const addTodoMutation = useMutation({
40 mutationFn: (newTodo) => axios.post('/api/data', { text: newTodo }),
41 // When mutate is called:
42 onMutate: async (newTodo: string) => {
43 setText('')
44 // Cancel any outgoing refetch
45 // (so they don't overwrite our optimistic update)
46 await queryClient.cancelQueries(todoListOptions)
47​
48 // Snapshot the previous value
49 const previousTodos = queryClient.getQueryData(todoListOptions.queryKey)
50​
51 // Optimistically update to the new value
52 if (previousTodos) {
53 queryClient.setQueryData(todoListOptions.queryKey, {
54 ...previousTodos,
55 items: [
56 ...previousTodos.items,
57 { id: Math.random().toString(), text: newTodo },
58 ],
59 })
60 }
61​
62 return { previousTodos }
63 },
64 // If the mutation fails,
65 // use the context returned from onMutate to roll back
66 onError: (err, variables, context) => {
67 if (context?.previousTodos) {
68 queryClient.setQueryData<Todos>(['todos'], context.previousTodos)
69 }
70 },
71 // Always refetch after error or success:
72 onSettled: () => {
73 queryClient.invalidateQueries({ queryKey: ['todos'] })
74 },
75 })
76​
77 return (
78 <div>
79 <p>
80 In this example, new items can be created using a mutation. The new item
81 will be optimistically added to the list in hopes that the server
82 accepts the item. If it does, the list is refetched with the true items
83 from the list. Every now and then, the mutation may fail though. When
84 that happens, the previous list of items is restored and the list is
85 again refetched from the server.
86 </p>
87 <form
88 onSubmit={(e) => {
89 e.preventDefault()
90 addTodoMutation.mutate(text)
91 }}
92 >
93 <input
94 type="text"
95 onChange={(event) => setText(event.target.value)}
96 value={text}
97 />
98 <button disabled={addTodoMutation.isPending}>Create</button>
99 </form>
100 <br />
101 {queryInfo.isSuccess && (
102 <>
103 <div>
104 {/* The type of queryInfo.data will be narrowed because we check for isSuccess first */}
105 Updated At: {new Date(queryInfo.data.ts).toLocaleTimeString()}
106 </div>
107 <ul>
108 {queryInfo.data.items.map((todo) => (
109 <li key={todo.id}>{todo.text}</li>
110 ))}
111 </ul>
112 {isFetching && <div>Updating in background...</div>}
113 </>
114 )}
115 {queryInfo.isLoading && 'Loading'}
116 {queryInfo.error instanceof Error && queryInfo.error.message}
117 </div>
118 )
120​
121export default function App() {
122 return (
123 <QueryClientProvider client={client}>
124 <Example />
125 <ReactQueryDevtools initialIsOpen />
126 </QueryClientProvider>
127 )