MCPcopy Create free account
hub / github.com/QuarkGluonPlasma/react-course-code / createStore

Function createStore

zustand-test/src/myZustand.js:3–40  ·  view source on GitHub ↗
(createState)

Source from the content-addressed store, hash-verified

1import { useSyncExternalStore } from "react";
2
3const createStore = (createState) => {
4 let state;
5 const listeners = new Set();
6
7 const setState = (partial, replace) => {
8 const nextState = typeof partial === 'function' ? partial(state) : partial
9
10 if (!Object.is(nextState, state)) {
11 const previousState = state;
12
13 if(!replace) {
14 state = (typeof nextState !== 'object' || nextState === null)
15 ? nextState
16 : Object.assign({}, state, nextState);
17 } else {
18 state = nextState;
19 }
20 listeners.forEach((listener) => listener(state, previousState));
21 }
22 }
23
24 const getState = () => state;
25
26 const subscribe= (listener) => {
27 listeners.add(listener)
28 return () => listeners.delete(listener)
29 }
30
31 const destroy= () => {
32 listeners.clear()
33 }
34
35 const api = { setState, getState, subscribe, destroy }
36
37 state = createState(setState, getState, api)
38
39 return api
40}
41
42function useStore(api, selector) {
43 function getState() {

Callers 1

createFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected