UNPKG

@undermuz/use-form

Version:
54 lines (53 loc) 1.73 kB
// src/utils/useReducer.ts import { useState, useCallback, useRef, useMemo } from "react"; function compose(...fns) { if (fns.length === 0) return (arg) => arg; if (fns.length === 1) return fns[0]; return fns.reduce( (a, b) => (...args) => a(b(...args)) ); } var useReducer = (reducer, initialState, middlewares = [], options) => { const initialStateRef = useRef(null); if (initialStateRef.current === null) { initialStateRef.current = { ...initialState }; if (options == null ? void 0 : options.debug) console.log("[useReducer][initialState]", initialStateRef.current); } const draftState = useRef(initialState); const [state, setState] = useState(() => { return draftState.current; }); const enhancedDispatch = useMemo(() => { const store2 = { getState: () => draftState.current, dispatch: (...args) => _enhancedDispatch(...args) }; const dispatch = (action) => { draftState.current = reducer(draftState.current, action); setState(draftState.current); return action; }; const chain = middlewares.map((middleware) => middleware(store2)); const _enhancedDispatch = compose(...chain)(dispatch); return _enhancedDispatch; }, []); const store = useMemo(() => { return { getState: () => draftState.current, dispatch: (...args) => enhancedDispatch(...args) }; }, []); const reset = useCallback(() => { draftState.current = initialStateRef.current; if (options == null ? void 0 : options.debug) console.log("[useReducer][Reset]", initialStateRef.current); setState(draftState.current); }, []); return [state, enhancedDispatch, { store, reset }]; }; export { useReducer };