File tree Expand file tree Collapse file tree 1 file changed +17
-0
lines changed Expand file tree Collapse file tree 1 file changed +17
-0
lines changed Original file line number Diff line number Diff line change @@ -2,10 +2,21 @@ import { useSyncExternalStore } from 'react'
22
33// https://react.dev/reference/react/useSyncExternalStore
44
5+ // Global item id
56let nextId = 0
7+
8+ // Global store containing an array of objects
69let todos = [ { id : nextId ++ , text : 'Todo #1' } ]
10+
11+ // Internal listeners for each method in todoStore initialized by useSyncExternalStore.
12+ // Needs to call emitChange() to take effect
713let listeners = [ ]
814
15+ /**
16+ * Exportable hook that uses useSyncExternalStore and a global variable to store data.
17+ * Usage: const { todos, addTodo, deleteTodo } = useTodos()
18+ * @returns {Object } { todos, addTodo, deleteTodo }
19+ */
920export default function useTodos ( ) {
1021 const todos = useSyncExternalStore (
1122 todoStore . subscribe ,
@@ -20,6 +31,12 @@ export default function useTodos () {
2031 }
2132}
2233
34+ /**
35+ * The external store with available useSyncExternalStore-required methods:
36+ * subscribe() - Used and initialized internally by useSyncExternalStore
37+ * getSnapshot() - Returns the current (full) snapshot of the global data variable
38+ * getServerSnapshot() - Used in SSR
39+ */
2340export const todoStore = {
2441 addTodo ( ) {
2542 todos = [ ...todos , { id : nextId ++ , text : 'Todo #' + nextId } ]
You can’t perform that action at this time.
0 commit comments