UNPKG

chromogen-zustand

Version:

simple, interaction-driven Jest test generator for Recoil and React Hooks apps

63 lines (62 loc) 2.54 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useHookedReducer = void 0; const react_1 = require("react"); const hooks_ledger_1 = require("../utils/hooks-ledger"); function useHookedReducer(reducer, initialState, store, reducerId) { const initialReducerState = (0, react_1.useMemo)(() => { const initialStateInStore = store.getState()[reducerId]; return initialStateInStore === undefined ? initialState : initialStateInStore; }, []); const [localState, setState] = (0, react_1.useState)(initialReducerState); store.subscribe(() => { hooks_ledger_1.hooksLedger.state = store.getState()[reducerId]; }); const dispatch = (0, react_1.useMemo)(() => { const dispatch = (action) => { if (action && typeof action === 'object' && typeof action.type === 'string') { store.dispatch({ type: `${reducerId}/${action.type}`, payload: action, }); } else { store.subscribe(() => { hooks_ledger_1.hooksLedger.state = store.getState()[reducerId]; ; hooks_ledger_1.hooksLedger.id = reducerId; hooks_ledger_1.hooksLedger.initialState = hooks_ledger_1.hooksLedger.state; }); store.subscribe(() => { hooks_ledger_1.hooksLedger.currState = hooks_ledger_1.hooksLedger.state; }); store.subscribe(() => { hooks_ledger_1.hooksLedger.dispCount = hooks_ledger_1.hooksLedger.dispCount + 1; }); store.dispatch({ type: reducerId, payload: action, }); } }; return dispatch; }, []); (0, react_1.useEffect)(() => { const teardown = store.registerHookedReducer(reducer, initialReducerState, reducerId); let lastReducerState = localState; const unsubscribe = store.subscribe(() => { const storeState = store.getState(); const reducerState = storeState[reducerId]; if (lastReducerState !== reducerState) { setState(reducerState); } lastReducerState = reducerState; }); return () => { unsubscribe(); teardown(); }; }, []); return [localState, dispatch]; } exports.useHookedReducer = useHookedReducer;