UNPKG

omnipay-savings-sdk

Version:

Omnipay Savings SDK

72 lines (71 loc) 2.37 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useAtom = exports.StoreProvider = void 0; const jsx_runtime_1 = require("react/jsx-runtime"); const react_1 = require("react"); const StoreContext = (0, react_1.createContext)(null); const StoreProvider = ({ children }) => { const state = (0, react_1.useRef)(new Map()); const subscribers = (0, react_1.useRef)(new Map()); const get = (key) => { return state.current.get(key); }; const set = (key, newValue) => { state.current.set(key, newValue); const subs = subscribers.current.get(key); if (subs) { subs.forEach(cb => cb()); } }; const subscribe = (key, callback) => { if (!subscribers.current.has(key)) { subscribers.current.set(key, []); } subscribers.current.get(key).push(callback); // Return unsubscribe fn return () => { const subs = subscribers.current.get(key); if (subs) { subscribers.current.set(key, subs.filter(cb => cb !== callback)); } }; }; const store = { get, set, subscribe, state: state.current, subscribers: subscribers.current, }; return ((0, jsx_runtime_1.jsx)(StoreContext.Provider, Object.assign({ value: store }, { children: children }))); }; exports.StoreProvider = StoreProvider; // Hook to read and subscribe to atom state function useAtom(key, defaultValue) { const store = (0, react_1.useContext)(StoreContext); if (!store) { throw new Error('useAtom must be used within a StoreProvider'); } const [value, setValue] = (0, react_1.useState)(() => { const existing = store.get(key); if (existing === undefined && defaultValue !== undefined) { store.set(key, defaultValue); return defaultValue; } return existing; }); (0, react_1.useEffect)(() => { // subscribe to changes on this atom key const unsubscribe = store.subscribe(key, () => { setValue(store.get(key)); }); return () => { unsubscribe(); }; }, [key, store]); const setter = (newValue) => { store.set(key, newValue); }; return [value, setter]; } exports.useAtom = useAtom;