( createMethods: CreateMethods<M, T>, initialState: T )
| 14 | }; |
| 15 | |
| 16 | const useMethods = <M, T>( |
| 17 | createMethods: CreateMethods<M, T>, |
| 18 | initialState: T |
| 19 | ): [T, WrappedMethods<M>] => { |
| 20 | const reducer = useMemo<Reducer<T, Action>>( |
| 21 | () => (reducerState: T, action: Action) => { |
| 22 | return createMethods(reducerState)[action.type](...action.payload); |
| 23 | }, |
| 24 | [createMethods] |
| 25 | ); |
| 26 | |
| 27 | const [state, dispatch] = useReducer<Reducer<T, Action>>(reducer, initialState); |
| 28 | |
| 29 | const wrappedMethods: WrappedMethods<M> = useMemo(() => { |
| 30 | const actionTypes = Object.keys(createMethods(initialState)); |
| 31 | |
| 32 | return actionTypes.reduce((acc, type) => { |
| 33 | acc[type] = (...payload) => dispatch({ type, payload }); |
| 34 | return acc; |
| 35 | }, {} as WrappedMethods<M>); |
| 36 | }, [createMethods, initialState]); |
| 37 | |
| 38 | return [state, wrappedMethods]; |
| 39 | }; |
| 40 | |
| 41 | export default useMethods; |
no test coverage detected
searching dependent graphs…