Todo Example

A simple todo app using @davstack/store, using React, typescript, tailwind.

Note: sometimes the codesandbox shows next.js hydration errors. This is not an issue with davstack store, and this error does not occur when running the code elsewhere..

Incase the codesandbox doesn't load, here is the code for the todo store:

todo-store.ts
import { store } from '@davstack/store';
 
export const todoStore = store({
	// Only need to cast the default value if the type can't be inferred
	todos: [] as Todo[],
}).extend((store) => ({
	addTodo(text: string) {
		// .set method uses immer, so we can mutate the draft while keeping state immutable
		store.set((draft) => {
			draft.todos.push({
				id: Date.now(),
				text,
				completed: false,
			});
		});
	},
	toggleTodo(id: number) {
		store.set((draft) => {
			const todo = draft.todos.find((todo) => todo.id === id);
			if (todo) {
				todo.completed = !todo.completed;
			}
		});
	},
	deleteTodo(id: number) {
		store.set((draft) => {
			const index = draft.todos.findIndex((todo) => todo.id === id);
			if (index !== -1) {
				draft.todos.splice(index, 1);
			}
		});
	},
}));
 
type Todo = {
	id: number;
	text: string;
	completed: boolean;
};