channelstate
Version:
A lightweight cross-context state management library built on the BroadcastChannel API.
23 lines (21 loc) • 734 B
JavaScript
function createStore(initialState) {
let state = initialState;
const listeners = /* @__PURE__ */ new Set();
const setState = (nextState, replace) => {
if (!Object.is(nextState, state)) {
const preState = state;
state = replace ?? (typeof nextState !== "object" || nextState === null) ? nextState : Object.assign({}, state, nextState);
for (const listener of listeners) {
listener(state, preState);
}
}
};
const getState = () => state;
const getInitialState = () => initialState;
const subscribe = (listener) => {
listeners.add(listener);
return () => listeners.delete(listener);
};
return { getState, getInitialState, setState, subscribe };
}
export { createStore };