Open History to see the last commit
1import React from 'react'
2import axios from 'axios'
3β
4//
5β
6import { useQuery, useMutation, queryCache } from 'react-query'
7β
8export default () => {
9 const [value, setValue] = React.useState('')
10β
11 const { status, data, error } = useQuery(
12 'todos',
13 async () => {
14 const { data } = await axios.get('/api/data')
15 return data
16 },
17 {
18 // Refetch the data every second
19 refetchInterval: 1000,
20 }
21 )
22β
23 const [mutateAddTodo] = useMutation(
24 value => fetch(`/api/data?add=${value}`),
25 {
26 onSuccess: () => queryCache.refetchQueries('todos'),
27 }
28 )
29β
30 const [mutateClear] = useMutation(value => fetch(`/api/data?clear=1`), {
31 onSuccess: () => queryCache.refetchQueries('todos'),
32 })
33β
34 if (status === 'loading') return <h1>Loading...</h1>
35 if (status === 'error') return <span>Error: {error.message}</span>
36β
37 return (
38 <div>
39 <h1>Auto Refetch with stale-time set to 1s)</h1>
40 <p>
41 This example is best experienced on your own machine, where you can open
42 multiple tabs to the same localhost server and see your changes
43 propagate between the two.
44 </p>
45 <h2>Todo List</h2>
46 <form
47 onSubmit={async ev => {
48 ev.preventDefault()
49 try {
50 await mutateAddTodo(value)
51 setValue('')
52 } catch {}
53 }}
54 >
55 <input
56 placeholder="enter something"
57 value={value}
58 onChange={ev => setValue(ev.target.value)}
59 />
60 </form>
61 <ul>
62 {data.map(item => (
63 <li key={item}>{item}</li>
64 ))}
65 </ul>
66 <div>
67 <button onClick={mutateClear}>Clear All</button>
68 </div>
69 </div>
70 )
71}