Skip to main content

Complete and delete

Add mutations that mark a todo done and delete it, and call them from the list.

Add two mutations: one marks a todo as done or not done, the other deletes it. The list from the previous page updates by itself after each one.

Add the mutations

Replace convex/todos.ts. list and create stay the same:

convex/todos.ts
import { ConvexError, v } from 'convex/values'

import { mutation, query } from './_generated/server'

// Public on purpose in this step: anyone can call these functions.
// "Protect data" adds an owner to each todo and checks the user.
export const list = query({
  args: {},
  handler: async (ctx) => {
    return await ctx.db.query('todos').order('desc').take(50)
  },
})

export const create = mutation({
  args: { text: v.string() },
  handler: async (ctx, args) => {
    const text = args.text.trim()
    if (!text || text.length > 200) {
      throw new ConvexError({
        code: 'INVALID_TODO_TEXT',
        message: 'Todo text must contain 1 to 200 characters',
      })
    }
    return await ctx.db.insert('todos', { text, completed: false })
  },
})

export const toggle = mutation({
  args: { todoId: v.id('todos') },
  handler: async (ctx, args) => {
    const todo = await ctx.db.get(args.todoId)
    if (!todo) throw new ConvexError({ code: 'TODO_NOT_FOUND', message: 'Todo not found' })
    await ctx.db.patch(todo._id, { completed: !todo.completed })
  },
})

export const remove = mutation({
  args: { todoId: v.id('todos') },
  handler: async (ctx, args) => {
    const todo = await ctx.db.get(args.todoId)
    if (!todo) throw new ConvexError({ code: 'TODO_NOT_FOUND', message: 'Todo not found' })
    await ctx.db.delete(todo._id)
  },
})

v.id('todos') accepts only the ID of a document in the todos table. Convex rejects any other value before the handler runs.

Call them from the list

Replace the page:

app/pages/index.vue
<script setup lang="ts">
import { api } from '#convex/api'

const text = ref('')
const { data: todos, status, error } = useConvexQuery(api.todos.list)
const {
  mutate: createTodo,
  pending: creating,
  error: createError,
} = useConvexMutation(api.todos.create)
const { mutate: toggleTodo, error: toggleError } = useConvexMutation(api.todos.toggle)
const { mutate: removeTodo, error: removeError } = useConvexMutation(api.todos.remove)
const callError = computed(() => createError.value ?? toggleError.value ?? removeError.value)

async function add() {
  try {
    await createTodo({ text: text.value })
    text.value = ''
  } catch {
    // createError holds the error. The template shows it.
  }
}
</script>

<template>
  <main>
    <h1>Todos</h1>

    <form @submit.prevent="add">
      <input v-model="text" maxlength="200" placeholder="What needs doing?" aria-label="Todo" />
      <button :disabled="creating || !text.trim()">Add</button>
    </form>
    <p v-if="callError" class="error">{{ callError.message }}</p>

    <p v-if="status === 'pending'" class="muted">Loading todos…</p>
    <p v-else-if="error" class="error">Could not load the todos.</p>
    <p v-else-if="todos?.length === 0" class="muted">No todos yet. Add the first one.</p>
    <ul v-else>
      <li v-for="todo in todos" :key="todo._id">
        <input
          type="checkbox"
          :checked="todo.completed"
          :aria-label="`Done: ${todo.text}`"
          @change="toggleTodo({ todoId: todo._id }).catch(() => {})"
        />
        <span :class="{ done: todo.completed }">{{ todo.text }}</span>
        <button @click="removeTodo({ todoId: todo._id }).catch(() => {})">Delete</button>
      </li>
    </ul>
  </main>
</template>

Each mutation keeps the error of its latest call in its error ref, and callError shows one of them. So the template only adds .catch(() => {}), which stops the rejected call from being reported as an unhandled error.

Try it

  1. Tick a todo. Its text is crossed out.
  2. Click Delete on a todo. It disappears.
  3. Do the same in a second tab. Both tabs show every change.

The page never updates the list itself. Each mutation changes the todos table, and Convex sends the new list result to every open page.

Your app now reads and writes live data. If it needs sign-in, continue with Add authentication. Otherwise, go to next steps.