-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
Copy pathuseMethods.ts
41 lines (32 loc) · 1.04 KB
/
useMethods.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import { Reducer, useMemo, useReducer } from 'react';
type Action = {
type: string;
payload?: any;
};
type CreateMethods<M, T> = (state: T) => {
[P in keyof M]: (payload?: any) => T;
};
type WrappedMethods<M> = {
[P in keyof M]: (...payload: any) => void;
};
const useMethods = <M, T>(
createMethods: CreateMethods<M, T>,
initialState: T
): [T, WrappedMethods<M>] => {
const reducer = useMemo<Reducer<T, Action>>(
() => (reducerState: T, action: Action) => {
return createMethods(reducerState)[action.type](...action.payload);
},
[createMethods]
);
const [state, dispatch] = useReducer<Reducer<T, Action>>(reducer, initialState);
const wrappedMethods: WrappedMethods<M> = useMemo(() => {
const actionTypes = Object.keys(createMethods(initialState));
return actionTypes.reduce((acc, type) => {
acc[type] = (...payload) => dispatch({ type, payload });
return acc;
}, {} as WrappedMethods<M>);
}, [createMethods, initialState]);
return [state, wrappedMethods];
};
export default useMethods;