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

App.tsx

95 lines2.6 KB

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