redext
Version:
A simple global store based on React Context and Hooks
72 lines (69 loc) • 1.94 kB
JavaScript
// src/Provider.tsx
import { useReducer, useRef } from "react";
// src/Context.tsx
import { createContext } from "react";
var Context_default = createContext({});
// src/Provider.tsx
import { jsx } from "react/jsx-runtime";
var Provider = (props) => {
const { store, initialValue, ...providerProps } = props;
if (!store) {
throw new Error("Please use <Provider store={...} initialValue={...}>");
}
const listeners = /* @__PURE__ */ new Set();
const initialState = store.getState(initialValue);
const [state, dispatch] = useReducer(store.getReducer, initialState);
const stateRef = useRef(initialState);
stateRef.current = state;
const getState = () => {
return stateRef.current;
};
const { effects, dispatch: dispatcher, models, on } = store.getEffect(dispatch, state);
const subscribe = (listener) => {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
};
const value = {
subscribe,
getState,
state: getState(),
dispatch: (arg) => {
on("onModel", (onModel) => {
var _a;
const type = arg == null ? void 0 : arg.type;
const types = (_a = type == null ? void 0 : type.split) == null ? void 0 : _a.call(type, "/");
const modelName = types == null ? void 0 : types[0];
if (!modelName) {
return;
}
const actionName = types == null ? void 0 : types[1];
const model = models[modelName];
onModel({
model: {
...model,
name: modelName
},
modelName,
actionName,
dispatch: dispatcher
});
});
dispatcher(arg);
listeners.forEach((listener) => listener());
},
effects
};
return /* @__PURE__ */ jsx(
Context_default.Provider,
{
value,
...providerProps
}
);
};
var Provider_default = Provider;
export {
Provider_default as default
};