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

TodoListUI.vue

67 lines1.8 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'
5​
6const queryClient = useQueryClient()
7const inputValue = ref('')
8​
9const { data: todos, suspense } = useQuery(todosQueries.list())
10​
11const { mutate, isPending, isError, error, variables } = useMutation({
12 ...todosMutations.create(),
13 onSettled: () =>
14 queryClient.invalidateQueries({ queryKey: todosQueries.list().queryKey }),
15})
16​
17await suspense()
18​
19const handleSubmit = () => {
20 const text = inputValue.value.trim()
21 if (!text) return
22 mutate(text)
23 inputValue.value = ''
25</script>
26​
27<template>
28 <div>
29 <p style="font-size: 0.875rem; color: #555; margin-bottom: 1rem">
30 <strong>Approach 1 — via UI variables:</strong> The pending item is
31 rendered directly from <code>mutation.variables</code>. No cache
32 manipulation needed. On error the pending item simply disappears.
33 </p>
34​
35 <form
36 style="display: flex; gap: 8px; margin-bottom: 1rem"
37 @submit.prevent="handleSubmit"
38 >
39 <input
40 v-model="inputValue"
41 placeholder="New todo…"
42 style="flex: 1; padding: 0.4rem 0.6rem; font-size: 1rem"
43 />
44 <button type="submit" :disabled="isPending">Add</button>
45 </form>
46​
47 <p v-if="isError" style="color: red; margin-bottom: 0.5rem">
48 {{ error?.message }}
49 </p>
50​
51 <ul style="list-style: none; padding: 0">
52 <li
53 v-for="todo in todos"
54 :key="todo.id"
55 style="padding: 0.4rem 0; border-bottom: 1px solid #eee"
56 >
57 {{ todo.text }}
58 </li>
59 <li
60 v-if="isPending"
61 style="padding: 0.4rem 0; border-bottom: 1px solid #eee; opacity: 0.5"
62 >
63 {{ variables }} <em>(saving…)</em>
64 </li>
65 </ul>
66 </div>
67</template>