Skip to main content

First real-time page

Add todos from a form and watch every open tab update live.

Build a todo list with a form. Nuxt renders the list on the server. Convex then keeps it live in every open tab.

Keep pnpm dev from the installation page running. Convex uploads each file in convex/ when you save it.

Define the table

convex/schema.ts
import { defineSchema, defineTable } from 'convex/server'
import { v } from 'convex/values'

export default defineSchema({
  todos: defineTable({
    text: v.string(),
    completed: v.boolean(),
  }),
})

Convex adds _id and _creationTime to every document.

Add the query and the mutation

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 })
  },
})

When you save, Convex generates api.todos.list and api.todos.create, and the pnpm dev output shows [convex] ✔ Convex functions ready!.

  • A query reads data. list returns the 50 newest todos. Older todos stay in the database but do not show; pagination loads them page by page.
  • A mutation writes data. create checks the text, then inserts a todo.

These functions are public on purpose: anyone can call them. Protect data adds an owner to each todo.

Render 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)

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="createError" class="error">{{ createError.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">
        <span>{{ todo.text }}</span>
      </li>
    </ul>
  </main>
</template>
  • useConvexQuery returns refs. data is undefined until the first result arrives. status is 'pending', 'success', 'error', or 'idle'.
  • useConvexMutation returns mutate, which calls the mutation and throws when it fails, and the refs pending, error, data and status. Rename them when a page has several mutations, as mutate: createTodo does here.
  • When create rejects the text, createError.message is the message from your ConvexError. See error handling.

See the live update

  1. Open http://localhost:3000. The page shows "No todos yet."
  2. Open the same address in a second browser tab, and put the two tabs side by side.
  3. Add a todo in one tab. It appears in both tabs.

You did not reload anything. Convex saw that create changed the todos table and sent the new list result to every open page.

See the server rendering

Reload the page and view its source (View Page Source in the browser). The todo text is in the HTML: Nuxt ran the query on the server before it sent the page. The same ref then subscribes over a WebSocket, so later changes arrive live. SSR, hydration, and real-time explains this in detail.

Next, complete and delete todos.