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

TodoListUI.tsx

88 lines2.5 KB

1import { useMutation, useQuery, useQueryClient } from '@tanstack/solid-query'
2import { For, Show, createSignal } from 'solid-js'
3import { todosMutations, todosQueries } from '~/services/todos/queries'
4import type { JSX } from 'solid-js'
5​
6export default function TodoListUI() {
7 const queryClient = useQueryClient()
8 const [inputValue, setInputValue] = createSignal('')
9​
10 const todosQuery = useQuery(() => ({
11 ...todosQueries.list(),
12 throwOnError: true,
13 }))
14​
15 const addTodoMutation = useMutation(() => ({
16 ...todosMutations.create(),
17 onSettled: () =>
18 queryClient.invalidateQueries({ queryKey: todosQueries.list().queryKey }),
19 }))
20​
21 const handleSubmit: JSX.EventHandler<HTMLFormElement, SubmitEvent> = (e) => {
22 e.preventDefault()
23 const text = inputValue().trim()
24 if (!text) return
25 addTodoMutation.mutate(text)
26 setInputValue('')
27 }
28​
29 return (
30 <div>
31 <p
32 style={{
33 'font-size': '0.875rem',
34 color: '#555',
35 'margin-bottom': '1rem',
36 }}
37 >
38 <strong>Approach 1 — via UI variables:</strong> The pending item is
39 rendered directly from <code>mutation.variables</code>. No cache
40 manipulation needed. On error the pending item simply disappears.
41 </p>
42​
43 <form
44 onSubmit={handleSubmit}
45 style={{ display: 'flex', gap: '8px', 'margin-bottom': '1rem' }}
46 >
47 <input
48 value={inputValue()}
49 onInput={(e) => setInputValue(e.currentTarget.value)}
50 placeholder="New todo…"
51 style={{ flex: 1, padding: '0.4rem 0.6rem', 'font-size': '1rem' }}
52 />
53 <button type="submit" disabled={addTodoMutation.isPending}>
54 Add
55 </button>
56 </form>
57​
58 <Show when={addTodoMutation.isError}>
59 <p style={{ color: 'red', 'margin-bottom': '0.5rem' }}>
60 {addTodoMutation.error?.message}
61 </p>
62 </Show>
63​
64 <ul style={{ 'list-style': 'none', padding: 0 }}>
65 <For each={todosQuery.data}>
66 {(todo) => (
67 <li
68 style={{ padding: '0.4rem 0', 'border-bottom': '1px solid #eee' }}
69 >
70 {todo.text}
71 </li>
72 )}
73 </For>
74 <Show when={addTodoMutation.isPending}>
75 <li
76 style={{
77 padding: '0.4rem 0',
78 'border-bottom': '1px solid #eee',
79 opacity: 0.5,
80 }}
81 >
82 {addTodoMutation.variables} <em>(saving…)</em>
83 </li>
84 </Show>
85 </ul>
86 </div>
87 )