Qume

Transform events into reactive application state

todoStore.ts
import { scope } from 'qume'

const { query, join, store, action } = scope<ToDoFact>()

type TodoEvent = 
  | { type: 'TODO_CREATED', id: string, text: string }
  | { type: 'TODO_COMPLETED', id: string }

const todoStore = store({
  // Queries transform events into state
  todos: query('TODO_CREATED').by.id,
  // Shows only todos that haven't been completed yet
  active: join({
    created: query('TODO_CREATED').by.id,
    completed: query('TODO_COMPLETED').by.id.optional()
  }).filter(({ completed }) => !completed).select.created
  // Action to create new todos
  create: action((title: string) => ({
    id: Math.random().toString(36),
    title: title,
  })).internal('TODO_CREATED'),
  // Action to complete todos
  complete: action((id: string) => ({ id }))
    .internal('TODO_COMPLETED'),
})