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

index.tsx

113 lines2.9 KB

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