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

index.tsx

93 lines2.9 KB

1import { ErrorBoundary, For, Suspense, createSignal } from 'solid-js'
2import { useMutation, useQuery, useQueryClient } from '@tanstack/solid-query'
3import { todosMutations, todosQueries } from '~/services/todos/queries'
4​
5export default function Example() {
6 const queryClient = useQueryClient()
7 const [intervalMs, setIntervalMs] = createSignal(1000)
8 const [value, setValue] = createSignal('')
9​
10 const todosQuery = useQuery(() => ({
11 ...todosQueries.list(),
12 // Refetch the data every second
13 refetchInterval: intervalMs(),
14 throwOnError: true,
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 return (
30 <ErrorBoundary fallback={(error) => <span>Error: {error.message}</span>}>
31 <Suspense fallback={<h1>Loading...</h1>}>
32 <div>
33 <h1>Auto Refetch with refetchInterval set to {intervalMs()}ms</h1>
34 <p>
35 This example is best experienced on your own machine, where you can
36 open multiple tabs to the same localhost server and see your changes
37 propagate between the two.
38 </p>
39 <label>
40 Query Interval speed (ms):{' '}
41 <input
42 value={intervalMs()}
43 onInput={(ev) => setIntervalMs(Number(ev.currentTarget.value))}
44 type="number"
45 step="100"
46 />{' '}
47 <span
48 style={{
49 display: 'inline-block',
50 'margin-left': '.5rem',
51 width: '10px',
52 height: '10px',
53 background: todosQuery.isFetching ? 'green' : 'transparent',
54 transition: !todosQuery.isFetching ? 'all .3s ease' : 'none',
55 'border-radius': '100%',
56 transform: 'scale(2)',
57 }}
58 />
59 </label>
60 <h2>Todo List</h2>
61 <form
62 onSubmit={(event) => {
63 event.preventDefault()
64 addMutation.mutate(value(), {
65 onSuccess: () => {
66 setValue('')
67 },
68 })
69 }}
70 >
71 <input
72 placeholder="enter something"
73 value={value()}
74 onInput={(ev) => setValue(ev.currentTarget.value)}
75 />
76 </form>
77 <ul>
78 <For each={todosQuery.data}>{(item) => <li>{item}</li>}</For>
79 </ul>
80 <div>
81 <button
82 onClick={() => {
83 clearMutation.mutate()
84 }}
85 >
86 Clear All
87 </button>
88 </div>
89 </div>
90 </Suspense>
91 </ErrorBoundary>
92 )