State Store

Having a global store can come in handy. There are many solutions out there you can use but let's entertain the idea you can create a simple store using the state function.

Let's create a todo store.

// src/stores/todo.ts
import {state} from "@beforesemicolon/markup";

type UUID = `${string}-${string}-${string}-${string}-${string}`

export interface Todo {
  id: UUID
  name: string
  description: string
  status: "done" | "pending" | "removed"
  dateCreated: Date
  dateLastUpdated: Date
}

const [todos, updateTodos] = state<Todo[]>([]);

export const todoList = todos;

export const createTodo = (name: string) => {
  const dateCreated = new Date();
  const todo: Todo = {
    id: crypto.randomUUID(),
    name,
    description: "",
    status: "pending",
    dateCreated,
    dateLastUpdated: dateCreated 
  }
  
  updateTodos(prev => [...prev, todo])
}

export const updateTodo = (id: UUID, data: Partial<Todo>) => {
  updateTodos(prev => prev.map(todo => {
    if(todo.id === id) {
      return {
        ...todo,
        name: data.name ?? todo.name,
        description: data.description ?? todo.description,
        status: data.status ?? todo.status,
        dateLastUpdated: new Date()
      }
    }
    
    return todo;
  }))
}

export const deleteTodo = (id: UUID) => {
  updateTodos(prev => prev.filter(todo => {
    return todo.id !== id;
  }))
}

export const clearTodos = () => {
  updateTodos([])
}

This is a simple file store that handles all the CRUD operations and only exposes the necessary.

There is no subscriptions needed, not complex setup and using the todoList in the template with the nice cocktail of helpers is all you need to create very complex applications.