Developers · Todo list

Todo list

A todo app with one collection. The example uses plain DOM code; use any UI library you like.

Store

// store.ts
import { Store } from '@civility/cloud'
import { IDBStorage } from '@civility/cloud/storage/idb'

export type Todo = { text: string; done: boolean; createdAt: string }

const store = new Store({
  id: 'app-k3m7q2x4p6w5z7n3b2v4c6h5', // from `civ id`
  storage: { db: new IDBStorage() },
  collections: ['todos'],
  versions: [{
    version: '1.0.0',
    schema: { type: 'object', properties: { todos: { type: 'object' } } },
  }],
})

export const todos = store.collection<Todo>('todos')

export function addTodo(text: string) {
  return todos.set(crypto.randomUUID(), {
    text,
    done: false,
    createdAt: new Date().toISOString(),
  })
}

export function toggleTodo(id: string, done: boolean) {
  return todos.update(id, { done })
}

export function removeTodo(id: string) {
  return todos.delete(id)
}

Create a record with set(id, value), change fields with update, and remove it with delete.

UI

<form id="new-todo"><input name="text" placeholder="New todo"></form>
<ul id="todos"></ul>
// main.ts
import { addTodo, removeTodo, todos, toggleTodo } from './store.ts'

const list = document.querySelector<HTMLUListElement>('#todos')!
const form = document.querySelector<HTMLFormElement>('#new-todo')!

function render() {
  list.replaceChildren(
    ...[...(todos.value ?? [])].map(([id, todo]) => {
      const checkbox = document.createElement('input')
      checkbox.type = 'checkbox'
      checkbox.checked = todo.done
      checkbox.onchange = () => toggleTodo(id, checkbox.checked)

      const remove = document.createElement('button')
      remove.textContent = 'Delete'
      remove.onclick = () => removeTodo(id)

      const item = document.createElement('li')
      item.append(checkbox, ` ${todo.text} `, remove)
      return item
    }),
  )
}

form.onsubmit = (event) => {
  event.preventDefault()
  const input = form.elements.namedItem('text') as HTMLInputElement
  const text = input.value.trim()
  if (text) addTodo(text)
  input.value = ''
}

await todos.preload() // fills todos.value
todos.subscribeAll(render)
render()

todos.value is a Map<string, Todo>. subscribeAll runs on every change, including changes pulled by sync.

Add sync

Replace Store with CloudStore and add cloud: { appId }. See Sync. Edits to different todos on two offline devices both survive the next sync.

Next: Journal