Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.cocobase.cc/llms.txt

Use this file to discover all available pages before exploring further.

Todo App Example

Build a complete todo application with authentication, real-time updates, and CRUD operations.

Features

  • User authentication
  • Create, read, update, delete todos
  • Mark todos as complete
  • Real-time sync across devices
  • Filter by status

Data Model

interface Todo {
  title: string;
  description?: string;
  completed: boolean;
  userId: string;
  createdAt: string;
  completedAt?: string;
}

Implementation

import { Cocobase } from "cocobase";

const db = new Cocobase({
  apiKey: process.env.COCOBASE_API_KEY,
});

// Authentication
async function register(email: string, password: string) {
  await db.auth.register({ email, password });
  return await db.auth.getUser();
}

async function login(email: string, password: string) {
  await db.auth.login({ email, password });
  return await db.auth.getUser();
}

// CRUD Operations
async function createTodo(title: string, description?: string) {
  const user = await db.auth.getUser();
  return await db.createDocument("todos", {
    title,
    description,
    completed: false,
    userId: user.id,
    createdAt: new Date().toISOString(),
  });
}

async function getTodos(filter?: "all" | "active" | "completed") {
  const user = await db.auth.getUser();
  const filters: any = {
    userId: user.id,
    orderBy: "createdAt",
    order: "desc",
  };

  if (filter === "active") {
    filters.completed = false;
  } else if (filter === "completed") {
    filters.completed = true;
  }

  return await db.listDocuments("todos", { filters });
}

async function toggleTodo(todoId: string) {
  const todo = await db.getDocument("todos", todoId);
  const completed = !todo.data.completed;

  return await db.updateDocument("todos", todoId, {
    completed,
    completedAt: completed ? new Date().toISOString() : null,
  });
}

async function deleteTodo(todoId: string) {
  return await db.deleteDocument("todos", todoId);
}

// Real-time sync
function watchTodos(callback: (todos: any[]) => void) {
  const user = db.auth.currentUser;
  return db.realtime.collection("todos", (event) => {
    // Refresh todos list on any change
    getTodos().then(callback);
  }, {
    filters: { userId: user?.id },
  });
}

Key Concepts Demonstrated

  1. Authentication - User registration and login
  2. CRUD Operations - Create, read, update, delete todos
  3. Filtering - Query by status (all, active, completed)
  4. Real-time Updates - Auto-sync across devices
  5. User Isolation - Each user sees only their todos

Next Steps

E-commerce App

Build a shopping application

Chat App

Build a real-time chat