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

index.tsx

104 lines3.0 KB

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