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

index.js

83 lines2.4 KB

1import React from 'react'
2import axios from 'axios'
3​
4import { useQuery, useMutation, queryCache } from 'react-query'
5​
6export default () => {
7 const [text, setText] = React.useState('')
8 const { status, data, error, isFetching } = useQuery('todos', async () => {
9 const { data } = await axios.get('/api/data')
10 return data
11 })
12​
13 const [mutatePostTodo] = useMutation(
14 text => axios.post('/api/data', { text }),
15 {
16 // Optimistically update the cache value on mutate, but store
17 // the old value and return it so that it's accessible in case of
18 // an error
19 onMutate: text => {
20 queryCache.cancelQueries('todos')
21​
22 const previousValue = queryCache.getQueryData('todos')
23​
24 queryCache.setQueryData('todos', old => ({
25 ...old,
26 items: [...old.items, text],
27 }))
28​
29 return previousValue
30 },
31 // On failure, roll back to the previous value
32 onError: (err, variables, previousValue) =>
33 queryCache.setQueryData('todos', previousValue),
34 onSuccess: () => {
35 setText('')
36 },
37 // After success or failure, refetch the todos query
38 onSettled: () => queryCache.refetchQueries('todos'),
39 }
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 mutatePostTodo(text)
56 }}
57 >
58 <input
59 type="text"
60 onChange={event => setText(event.target.value)}
61 value={text}
62 />
63 <button>Create</button>
64 </form>
65 <br />
66 {status === 'loading' ? (
67 'Loading...'
68 ) : status === 'error' ? (
69 error.message
70 ) : (
71 <>
72 <div>Updated At: {new Date(data.ts).toLocaleTimeString()}</div>
73 <ul>
74 {data.items.map(datum => (
75 <li key={datum}>{datum}</li>
76 ))}
77 </ul>
78 <div>{isFetching ? 'Updating in background...' : ' '}</div>
79 </>
80 )}
81 </div>
82 )