Open History to see the last commit
1import { LitElement, html } from 'lit'
2import {
3 createMutationController,
4 createQueryController,
5} from '@tanstack/lit-query'
6import { todosMutations, todosQueries } from './services/todos/queries'
7
8class TodoListUI extends LitElement {
9 static properties = {
10 inputValue: { state: true },
11 }
12
13 private inputValue = ''
14
15 private readonly todos = createQueryController(this, todosQueries.list())
16
17 private readonly addTodoMutation = createMutationController(this, () => ({
18 ...todosMutations.create(),
19 onSettled: (_data, _error, _variables, _onMutateResult, { client }) =>
20 client.invalidateQueries({ queryKey: todosQueries.list().queryKey }),
21 }))
22
23 protected override createRenderRoot(): HTMLElement | DocumentFragment {
24 return this
25 }
26
27 private handleSubmit(event: SubmitEvent) {
28 event.preventDefault()
29 const text = this.inputValue.trim()
30 if (!text) return
31 this.addTodoMutation.mutate(text)
32 this.inputValue = ''
33 }
34
35 render() {
36 const { status, data: todos, error } = this.todos()
37 const addTodoMutation = this.addTodoMutation()
38
39 if (status === 'pending') return html`<p>Loading todos…</p>`
40 if (status === 'error') return html`<p>Error: ${error.message}</p>`
41
42 return html`
43 <div>
44 <p style="font-size: 0.875rem; color: #555; margin-bottom: 1rem">
45 <strong>Approach 1 — via UI variables:</strong> The pending item is
46 rendered directly from <code>mutation.variables</code>. No cache
47 manipulation needed. On error the pending item simply disappears.
48 </p>
49
50 <form
51 @submit=${this.handleSubmit}
52 style="display: flex; gap: 8px; margin-bottom: 1rem"
53 >
54 <input
55 .value=${this.inputValue}
56 @input=${(event: Event) =>
57 (this.inputValue = (
58 event.currentTarget as HTMLInputElement
59 ).value)}
60 placeholder="New todo…"
61 style="flex: 1; padding: 0.4rem 0.6rem; font-size: 1rem"
62 />
63 <button type="submit" ?disabled=${addTodoMutation.isPending}>
64 Add
65 </button>
66 </form>
67
68 ${
69 addTodoMutation.isError
70 ? html`<p style="color: red; margin-bottom: 0.5rem">
71 ${addTodoMutation.error.message}
72 </p>`
73 : null
74 }
75
76 <ul style="list-style: none; padding: 0">
77 ${todos.map(
78 (todo) => html`
79 <li style="padding: 0.4rem 0; border-bottom: 1px solid #eee">
80 ${todo.text}
81 </li>
82 `,
83 )}
84 ${
85 addTodoMutation.isPending
86 ? html`
87 <li
88 style="padding: 0.4rem 0; border-bottom: 1px solid #eee; opacity: 0.5"
89 >
90 ${addTodoMutation.variables} <em>(saving…)</em>
91 </li>
92 `
93 : null
94 }
95 </ul>
96 </div>
97 `
98 }
99}
100
101customElements.define('todo-list-ui', TodoListUI)