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

index.tsx

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