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

App.tsx

96 lines2.6 KB

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