import {ComputedRef} from 'vue'; import {useReducer} from "./index"; import {Reducer} from './misc/types'; type Action = { type: string; payload?: any; }; type CreateMethods = ( state: T ) => { [P in keyof M]: (payload?: any) => T; }; type WrappedMethods = { [P in keyof M]: (...payload: any) => void; }; const useMethods = ( createMethods: CreateMethods, initialState: T ): [ComputedRef, WrappedMethods] => { const reducer: Reducer = (reducerState: T, action: Action) => { return createMethods(reducerState)[action.type](...action.payload); }; const [state, dispatch] = useReducer>(reducer, initialState); const wrappedMethods: WrappedMethods = (() => { const actionTypes = Object.keys(createMethods(initialState)); return actionTypes.reduce((acc, type) => { acc[type] = (...payload) => dispatch({type, payload}); return acc; }, {} as WrappedMethods); })(); return [state, wrappedMethods]; }; export default useMethods;