-
Notifications
You must be signed in to change notification settings - Fork 5
/
store.tsx
36 lines (29 loc) · 1.03 KB
/
store.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
import React, { FC, createContext, useReducer, ReactNode } from 'react';
interface StateData {
account: { addr: string; shard: string } | undefined;
}
const typeStateMap = {
SET_ACCOUNT: 'account',
};
const initialState: StateData = {
account: undefined,
};
const reducer = (state: StateData, action: { type: keyof typeof typeStateMap; payload: any }) => {
const stateName = typeStateMap[action.type];
if (!stateName) {
console.warn(`Unknown action type: ${action.type}`);
return state;
}
return { ...state, [stateName]: action.payload };
};
const StateContext = createContext(initialState);
const DispatchContext = createContext<any>(null);
const StateProvider: FC<{ children?: ReactNode }> = ({ children }) => {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<DispatchContext.Provider value={dispatch}>
<StateContext.Provider value={state}>{children}</StateContext.Provider>
</DispatchContext.Provider>
);
};
export { typeStateMap, StateContext, DispatchContext, StateProvider };