Skip to content

Instantly share code, notes, and snippets.

@alissaVrk
Last active March 20, 2023 06:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alissaVrk/145738903210725bf2ed38dee41571da to your computer and use it in GitHub Desktop.
Save alissaVrk/145738903210725bf2ed38dee41571da to your computer and use it in GitHub Desktop.
TodoProvider with a simple reactive store
import React, { PropsWithChildren, useMemo } from 'react';
import { createSimpleReactiveStore } from './simple-reactive-store';
export type Todo = {
id: string;
name: string;
};
export type TodoAPI = {
addTodo: (todo: Todo) => void;
setTodo: (todo: Todo) => void;
useTodo: (id: string) => Todo | undefined;
useTodoList: () => string[];
};
const TodoContext = React.createContext<TodoAPI>({} as TodoAPI);
const TODO_LIST_PATH = 'todoList';
export function TodoProvider(props: PropsWithChildren<{}>) {
const store = useMemo(() => createSimpleReactiveStore(), []);
const api = useMemo(
() => ({
addTodo: (todo: Todo) => {
const list = store.getValue<string[]>(TODO_LIST_PATH) || [];
store.setValue(TODO_LIST_PATH, [...list, todo.id]);
store.setValue(todo.id, todo);
},
setTodo: (todo: Todo) => store.setValue(todo.id, todo),
useTodo: (id: string) => store.useValue<Todo | undefined>(id, undefined),
useTodoList: () => store.useValue<string[]>(TODO_LIST_PATH, []),
}),
[store],
);
return <TodoContext.Provider value={api}>{props.children}</TodoContext.Provider>;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment