@naverpay/vanilla-store
Version:
  
65 lines (62 loc) • 1.92 kB
JavaScript
import { applyPersist } from "./applyOptions.mjs";
import { shallowEqual } from "./shallowEqual.mjs";
const isServer = typeof window === "undefined";
const createVanillaStore = (initialState, equalityFn = shallowEqual, options) => {
let state = initialState;
const callbacks = /* @__PURE__ */ new Set();
const get = () => state;
const set = (nextState) => {
const next = typeof nextState === "function" ? nextState(state) : nextState;
if (!equalityFn(next, state)) {
state = next;
callbacks.forEach((callback) => callback());
}
return state;
};
let persistStore = null;
const addCallbacks = () => callbacks.add(() => {
if (persistStore) {
persistStore.value = get();
}
});
const subscribe = (callback) => {
callbacks.add(callback);
return () => {
callbacks.delete(callback);
};
};
const storeBase = {
get,
set,
subscribe
};
if (isServer) {
return {
get: storeBase.get,
set: () => {
const setInServerError = new Error("[@naverpay/vanilla-store] The set method can only be called from the client");
const stack = setInServerError.stack;
console.error(`
╔═══════════════════════════════════════════╗
║ SERVER STORE ERROR ║
╚═══════════════════════════════════════════╝
⚠️ ${setInServerError.message}
%cSTACK TRACE%c
---------------
${stack}
`, "font-weight: bold; color: red;", "font-weight: normal;");
return initialState;
},
subscribe: storeBase.subscribe,
persistStore: null
};
}
persistStore = applyPersist(options, addCallbacks, initialState);
return {
...storeBase,
persistStore
};
};
export {
createVanillaStore
};