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
| // store.tsx
import React, { createContext, useReducer } from 'react';
export const ActionType: { [key: string]: string } = {
onLogin: 'LOGIN',
onLogout: 'LOGOUT',
};
interface State {
token?: string;
state?: State;
dispatch?: React.Dispatch<Action>;
}
interface Action {
type: string;
token?: string;
}
const initialState: State = {};
const store = createContext(initialState);
const { Provider } = store;
const StateProvider = (props: {
children: JSX.Element | undefined;
}): JSX.Element => {
const { children } = props;
const [state, dispatch] = useReducer(
(states: State, action: Action): State => {
const { type, token } = action;
switch (type) {
case ActionType.onLogin:
return {
...states,
token,
};
case ActionType.onLogout:
return {
...states,
token: '',
};
default:
return {
...states,
};
}
},
initialState,
);
return <Provider value={{ state, dispatch }}>{children}</Provider>;
};
export { store, StateProvider };
|