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

todo-list-cache.ts

144 lines4.2 KB

1import {
2 createMutationController,
3 createQueryController,
4} from '@tanstack/lit-query'
5import { LitElement, html } from 'lit'
6import { todosMutations, todosQueries } from './services/todos/queries'
7import type { Todo } from './services/todos/types'
8​
9interface MutationContext {
10 previousTodos: Array<Todo> | undefined
11 optimisticId: string
13​
14class TodoListCache extends LitElement {
15 static properties = {
16 inputValue: { state: true },
17 lastError: { state: true },
18 }
19​
20 private inputValue = ''
21 private lastError: string | null = null
22​
23 private readonly todos = createQueryController(this, todosQueries.list())
24​
25 private readonly addTodoMutation = createMutationController<
26 Todo,
27 Error,
28 string,
29 MutationContext
30 >(this, () => ({
31 ...todosMutations.create(),
32 onMutate: async (text, { client }) => {
33 this.lastError = null
34 await client.cancelQueries({
35 queryKey: todosQueries.list().queryKey,
36 })
37​
38 const previousTodos = client.getQueryData(todosQueries.list().queryKey)
39​
40 const optimisticId = `optimistic-${Date.now()}`
41 const optimisticTodo: Todo = {
42 id: optimisticId,
43 text,
44 createdAt: Date.now(),
45 }
46​
47 client.setQueryData(todosQueries.list().queryKey, (old = []) => [
48 ...old,
49 optimisticTodo,
50 ])
51​
52 return { previousTodos, optimisticId }
53 },
54 onError: (_err, _text, context, { client }) => {
55 this.lastError = _err.message
56 if (context?.previousTodos !== undefined) {
57 client.setQueryData(todosQueries.list().queryKey, context.previousTodos)
58 } else if (context?.optimisticId) {
59 client.setQueryData(todosQueries.list().queryKey, (old = []) =>
60 old.filter((todo) => todo.id !== context.optimisticId),
61 )
62 }
63 },
64 onSettled: (_data, _error, _variables, _context, { client }) =>
65 client.invalidateQueries({ queryKey: todosQueries.list().queryKey }),
66 }))
67​
68 protected override createRenderRoot(): HTMLElement | DocumentFragment {
69 return this
70 }
71​
72 private handleSubmit(event: SubmitEvent) {
73 event.preventDefault()
74 const text = this.inputValue.trim()
75 if (!text) return
76 this.addTodoMutation.mutate(text)
77 this.inputValue = ''
78 }
79​
80 render() {
81 const { status, data: todos, error } = this.todos()
82 const addTodoMutation = this.addTodoMutation()
83​
84 if (status === 'pending') return html`<p>Loading todos…</p>`
85 if (status === 'error') return html`<p>Error: ${error.message}</p>`
86​
87 return html`
88 <div>
89 <p style="font-size: 0.875rem; color: #555; margin-bottom: 1rem">
90 <strong>Approach 2 — via cache manipulation:</strong>
91 <code>onMutate</code> snapshots the cache and writes the optimistic
92 item in. <code>onError</code> restores the snapshot on failure.
93 </p>
94​
95 <form
96 @submit=${this.handleSubmit}
97 style="display: flex; gap: 8px; margin-bottom: 1rem"
98 >
99 <input
100 .value=${this.inputValue}
101 @input=${(event: Event) =>
102 (this.inputValue = (
103 event.currentTarget as HTMLInputElement
104 ).value)}
105 placeholder="New todo…"
106 style="flex: 1; padding: 0.4rem 0.6rem; font-size: 1rem"
107 />
108 <button type="submit" ?disabled=${addTodoMutation.isPending}>
109 Add
110 </button>
111 </form>
112​
113 ${
114 this.lastError
115 ? html`<p style="color: red; margin-bottom: 0.5rem">
116 ${this.lastError}
117 </p>`
118 : null
119 }
120​
121 <ul style="list-style: none; padding: 0">
122 ${todos.map(
123 (todo) => html`
124 <li
125 style="padding: 0.4rem 0; border-bottom: 1px solid #eee; opacity: ${
126 todo.id.startsWith('optimistic-') ? 0.5 : 1
127 }"
128 >
129 ${todo.text}
130 ${
131 todo.id.startsWith('optimistic-')
132 ? html`<em> (saving…)</em>`
133 : null
134 }
135 </li>
136 `,
137 )}
138 </ul>
139 </div>
140 `
141 }
143​
144customElements.define('todo-list-cache', TodoListCache)