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

TodoListCache.vue

112 lines3.1 KB

1<script setup lang="ts">
2import { ref } from 'vue'
3import { useMutation, useQuery, useQueryClient } from '@tanstack/vue-query'
4import { todosMutations, todosQueries } from '../services/todos/queries'
5import type { Todo } from '../services/todos/types'
6​
7interface MutationContext {
8 previousTodos: Array<Todo> | undefined
9 optimisticId: string
11​
12const queryClient = useQueryClient()
13const inputValue = ref('')
14const lastError = ref<string | null>(null)
15​
16const { data: todos, suspense } = useQuery(todosQueries.list())
17​
18const { mutate, isPending } = useMutation<Todo, Error, string, MutationContext>(
19 {
20 ...todosMutations.create(),
21 onMutate: async (text) => {
22 lastError.value = null
23 await queryClient.cancelQueries({
24 queryKey: todosQueries.list().queryKey,
25 })
26​
27 const previousTodos = queryClient.getQueryData(
28 todosQueries.list().queryKey,
29 )
30​
31 const optimisticId = `optimistic-${Date.now()}`
32 const optimisticTodo: Todo = {
33 id: optimisticId,
34 text,
35 createdAt: Date.now(),
36 }
37​
38 queryClient.setQueryData(todosQueries.list().queryKey, (old = []) => [
39 ...old,
40 optimisticTodo,
41 ])
42​
43 return { previousTodos, optimisticId }
44 },
45 onError: (_err, _text, context) => {
46 lastError.value = _err.message
47 if (context?.previousTodos !== undefined) {
48 queryClient.setQueryData(
49 todosQueries.list().queryKey,
50 context.previousTodos,
51 )
52 } else if (context?.optimisticId) {
53 queryClient.setQueryData(todosQueries.list().queryKey, (old = []) =>
54 old.filter((todo) => todo.id !== context.optimisticId),
55 )
56 }
57 },
58 onSettled: () =>
59 queryClient.invalidateQueries({ queryKey: todosQueries.list().queryKey }),
60 },
62​
63await suspense()
64​
65const handleSubmit = () => {
66 const text = inputValue.value.trim()
67 if (!text) return
68 mutate(text)
69 inputValue.value = ''
71</script>
72​
73<template>
74 <div>
75 <p style="font-size: 0.875rem; color: #555; margin-bottom: 1rem">
76 <strong>Approach 2 — via cache manipulation:</strong>
77 <code>onMutate</code> snapshots the cache and writes the optimistic item
78 in. <code>onError</code> restores the snapshot on failure.
79 </p>
80​
81 <form
82 style="display: flex; gap: 8px; margin-bottom: 1rem"
83 @submit.prevent="handleSubmit"
84 >
85 <input
86 v-model="inputValue"
87 placeholder="New todo…"
88 style="flex: 1; padding: 0.4rem 0.6rem; font-size: 1rem"
89 />
90 <button type="submit" :disabled="isPending">Add</button>
91 </form>
92​
93 <p v-if="lastError" style="color: red; margin-bottom: 0.5rem">
94 {{ lastError }}
95 </p>
96​
97 <ul style="list-style: none; padding: 0">
98 <li
99 v-for="todo in todos"
100 :key="todo.id"
101 :style="{
102 padding: '0.4rem 0',
103 borderBottom: '1px solid #eee',
104 opacity: todo.id.startsWith('optimistic-') ? 0.5 : 1,
105 }"
106 >
107 {{ todo.text }}
108 <em v-if="todo.id.startsWith('optimistic-')"> (saving…)</em>
109 </li>
110 </ul>
111 </div>
112</template>