MCPcopy
hub / github.com/TanStack/query / Example

Function Example

examples/react/auto-refetching/src/pages/index.tsx:22–113  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

20}
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>

Callers

nothing calls this directly

Calls 5

useQueryClientFunction · 0.90
useQueryFunction · 0.90
useMutationFunction · 0.90
invalidateQueriesMethod · 0.45
mutateMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…