@naverpay/vanilla-store
Version:
  
65 lines (62 loc) • 2.05 kB
JavaScript
;
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const applyOptions = require("./applyOptions.js");
const shallowEqual = require("./shallowEqual.js");
const isServer = typeof window === "undefined";
const createVanillaStore = (initialState, equalityFn = shallowEqual.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 = applyOptions.applyPersist(options, addCallbacks, initialState);
return {
...storeBase,
persistStore
};
};
exports.createVanillaStore = createVanillaStore;