Last active
March 20, 2023 06:12
-
-
Save alissaVrk/145738903210725bf2ed38dee41571da to your computer and use it in GitHub Desktop.
TodoProvider with a simple reactive store
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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