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

index.js

103 lines2.8 KB

1import React from 'react'
2import axios from 'axios'
3​
4import {
5 useQuery,
6 useQueryClient,
7 useMutation,
8 QueryClient,
9 QueryClientProvider,
10} from 'react-query'
11import { ReactQueryDevtools } from 'react-query/devtools'
12​
13const queryClient = new QueryClient()
14​
15export default function App() {
16 return (
17 <QueryClientProvider client={queryClient}>
18 <Example />
19 </QueryClientProvider>
20 )
22​
23function Example() {
24 const queryClient = useQueryClient()
25 const [text, setText] = React.useState('')
26​
27 const { status, data, error, isFetching } = useQuery('todos', async () => {
28 const res = await axios.get('/api/data')
29 return res.data
30 })
31​
32 const addTodoMutation = useMutation(
33 text => axios.post('/api/data', { text }),
34 {
35 // Optimistically update the cache value on mutate, but store
36 // the old value and return it so that it's accessible in case of
37 // an error
38 onMutate: async text => {
39 setText('')
40 await queryClient.cancelQueries('todos')
41​
42 const previousValue = queryClient.getQueryData('todos')
43​
44 queryClient.setQueryData('todos', old => ({
45 ...old,
46 items: [...old.items, text],
47 }))
48​
49 return previousValue
50 },
51 // On failure, roll back to the previous value
52 onError: (err, variables, previousValue) =>
53 queryClient.setQueryData('todos', previousValue),
54 // After success or failure, refetch the todos query
55 onSettled: () => {
56 queryClient.invalidateQueries('todos')
57 },
58 }
59 )
60​
61 return (
62 <div>
63 <p>
64 In this example, new items can be created using a mutation. The new item
65 will be optimistically added to the list in hopes that the server
66 accepts the item. If it does, the list is refetched with the true items
67 from the list. Every now and then, the mutation may fail though. When
68 that happens, the previous list of items is restored and the list is
69 again refetched from the server.
70 </p>
71 <form
72 onSubmit={e => {
73 e.preventDefault()
74 addTodoMutation.mutate(text)
75 }}
76 >
77 <input
78 type="text"
79 onChange={event => setText(event.target.value)}
80 value={text}
81 />
82 <button>{addTodoMutation.isLoading ? 'Creating...' : 'Create'}</button>
83 </form>
84 <br />
85 {status === 'loading' ? (
86 'Loading...'
87 ) : status === 'error' ? (
88 error.message
89 ) : (
90 <>
91 <div>Updated At: {new Date(data.ts).toLocaleTimeString()}</div>
92 <ul>
93 {data.items.map(datum => (
94 <li key={datum}>{datum}</li>
95 ))}
96 </ul>
97 <div>{isFetching ? 'Updating in background...' : ' '}</div>
98 </>
99 )}
100 <ReactQueryDevtools initialIsOpen />
101 </div>
102 )