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

TodoListCache.tsx

130 lines3.8 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'
5import type { Todo } from '~/services/todos/types'
6​
7interface MutationContext {
8 previousTodos: Array<Todo> | undefined
9 optimisticId: string
11​
12export default function TodoListCache() {
13 const queryClient = useQueryClient()
14 const [inputValue, setInputValue] = createSignal('')
15 const [lastError, setLastError] = createSignal<string | null>(null)
16​
17 const todosQuery = useQuery(() => ({
18 ...todosQueries.list(),
19 throwOnError: true,
20 }))
21​
22 const addTodoMutation = useMutation<Todo, Error, string, MutationContext>(
23 () => ({
24 ...todosMutations.create(),
25 onMutate: async (text) => {
26 setLastError(null)
27 await queryClient.cancelQueries({
28 queryKey: todosQueries.list().queryKey,
29 })
30​
31 const previousTodos = queryClient.getQueryData(
32 todosQueries.list().queryKey,
33 )
34​
35 const optimisticId = `optimistic-${Date.now()}`
36 const optimisticTodo: Todo = {
37 id: optimisticId,
38 text,
39 createdAt: Date.now(),
40 }
41​
42 queryClient.setQueryData(todosQueries.list().queryKey, (old = []) => [
43 ...old,
44 optimisticTodo,
45 ])
46​
47 return { previousTodos, optimisticId }
48 },
49 onError: (_err, _text, context) => {
50 setLastError(_err.message)
51 if (context?.previousTodos !== undefined) {
52 queryClient.setQueryData(
53 todosQueries.list().queryKey,
54 context.previousTodos,
55 )
56 } else if (context?.optimisticId) {
57 queryClient.setQueryData(todosQueries.list().queryKey, (old = []) =>
58 old.filter((todo) => todo.id !== context.optimisticId),
59 )
60 }
61 },
62 onSettled: () =>
63 queryClient.invalidateQueries({
64 queryKey: todosQueries.list().queryKey,
65 }),
66 }),
67 )
68​
69 const handleSubmit: JSX.EventHandler<HTMLFormElement, SubmitEvent> = (e) => {
70 e.preventDefault()
71 const text = inputValue().trim()
72 if (!text) return
73 addTodoMutation.mutate(text)
74 setInputValue('')
75 }
76​
77 return (
78 <div>
79 <p
80 style={{
81 'font-size': '0.875rem',
82 color: '#555',
83 'margin-bottom': '1rem',
84 }}
85 >
86 <strong>Approach 2 — via cache manipulation:</strong>{' '}
87 <code>onMutate</code> snapshots the cache and writes the optimistic item
88 in. <code>onError</code> restores the snapshot on failure.
89 </p>
90​
91 <form
92 onSubmit={handleSubmit}
93 style={{ display: 'flex', gap: '8px', 'margin-bottom': '1rem' }}
94 >
95 <input
96 value={inputValue()}
97 onInput={(e) => setInputValue(e.currentTarget.value)}
98 placeholder="New todo…"
99 style={{ flex: 1, padding: '0.4rem 0.6rem', 'font-size': '1rem' }}
100 />
101 <button type="submit" disabled={addTodoMutation.isPending}>
102 Add
103 </button>
104 </form>
105​
106 <Show when={lastError()}>
107 <p style={{ color: 'red', 'margin-bottom': '0.5rem' }}>{lastError()}</p>
108 </Show>
109​
110 <ul style={{ 'list-style': 'none', padding: 0 }}>
111 <For each={todosQuery.data}>
112 {(todo) => (
113 <li
114 style={{
115 padding: '0.4rem 0',
116 'border-bottom': '1px solid #eee',
117 opacity: todo.id.startsWith('optimistic-') ? 0.5 : 1,
118 }}
119 >
120 {todo.text}
121 <Show when={todo.id.startsWith('optimistic-')}>
122 <em> (saving…)</em>
123 </Show>
124 </li>
125 )}
126 </For>
127 </ul>
128 </div>
129 )