-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.tsx
58 lines (48 loc) · 1.36 KB
/
index.tsx
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import * as React from 'react';
export const actions = {
SET_STATE: 'SET_STATE',
};
export const StoreContext = React.createContext<any>({});
export interface StoreProviderProps<T> {
initialState: T,
reducer?: T,
children: React.ReactNode | React.ReactNode[] | null;
}
export const StoreProvider: React.FC<StoreProviderProps<any>> = (props) => {
const reducer = React.useCallback((s, a) => {
const { type, payload } = a;
switch (type) {
case actions.SET_STATE:
if (payload instanceof Array) {
const obj = { ...s };
a.payload.map((v) => {
obj[v.name] = v.value;
});
return obj;
} else {
return {
...s,
[payload.name]: payload.value,
};
}
default: return props.reducer ? props.reducer(s, a) : s;
}
}, []);
const [state, dispatch] = React.useReducer<React.Reducer<any, React.ReducerAction<any>>>(reducer, props.initialState);
return (
<StoreContext.Provider value={{ state, dispatch }}>
{props.children}
</StoreContext.Provider>
);
};
export const useStore = () => {
const { state, dispatch } = React.useContext(StoreContext);
const dispatchState = React.useCallback((payload) => {
dispatch({ type: actions.SET_STATE, payload });
}, []);
return {
state,
dispatch,
dispatchState,
};
};