Open History to see the last commit
1import React from 'react'
2import axios from 'axios'
3β
4//
5β
6import {
7 useQuery,
8 useQueryClient,
9 useMutation,
10 QueryClient,
11 QueryClientProvider,
12} from '@tanstack/react-query'
13import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
14β
15const queryClient = new QueryClient()
16β
17export default function App() {
18 return (
19 <QueryClientProvider client={queryClient}>
20 <Example />
21 </QueryClientProvider>
22 )
23}
24β
25function Example() {
26 const queryClient = useQueryClient()
27 const [intervalMs, setIntervalMs] = React.useState(1000)
28 const [value, setValue] = React.useState('')
29β
30 const { status, data, error, isFetching } = useQuery({
31 queryKey: ['todos'],
32 queryFn: async () => {
33 const res = await axios.get('/api/data')
34 return res.data
35 },
36 // Refetch the data every second
37 refetchInterval: intervalMs,
38 })
39β
40 const addMutation = useMutation({
41 mutationFn: (add) => fetch(`/api/data?add=${add}`),
42 onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
43 })
44β
45 const clearMutation = useMutation({
46 mutationFn: () => fetch(`/api/data?clear=1`),
47 onSuccess: () => queryClient.invalidateQueries({ queryKey: ['todos'] }),
48 })
49β
50 if (status === 'loading') return <h1>Loading...</h1>
51 if (status === 'error') return <span>Error: {error.message}</span>
52β
53 return (
54 <div>
55 <h1>Auto Refetch with stale-time set to 1s)</h1>
56 <p>
57 This example is best experienced on your own machine, where you can open
58 multiple tabs to the same localhost server and see your changes
59 propagate between the two.
60 </p>
61 <label>
62 Query Interval speed (ms):{' '}
63 <input
64 value={intervalMs}
65 onChange={(ev) => setIntervalMs(Number(ev.target.value))}
66 type="number"
67 step="100"
68 />{' '}
69 <span
70 style={{
71 display: 'inline-block',
72 marginLeft: '.5rem',
73 width: 10,
74 height: 10,
75 background: isFetching ? 'green' : 'transparent',
76 transition: !isFetching ? 'all .3s ease' : 'none',
77 borderRadius: '100%',
78 transform: 'scale(2)',
79 }}
80 />
81 </label>
82 <h2>Todo List</h2>
83 <form
84 onSubmit={(event) => {
85 event.preventDefault()
86 addMutation.mutate(value, {
87 onSuccess: () => {
88 setValue('')
89 },
90 })
91 }}
92 >
93 <input
94 placeholder="enter something"
95 value={value}
96 onChange={(ev) => setValue(ev.target.value)}
97 />
98 </form>
99 <ul>
100 {data.map((item) => (
101 <li key={item}>{item}</li>
102 ))}
103 </ul>
104 <div>
105 <button
106 onClick={() => {
107 clearMutation.mutate()
108 }}
109 >
110 Clear All
111 </button>
112 </div>
113 <ReactQueryDevtools initialIsOpen />
114 </div>
115 )
116}