-
Notifications
You must be signed in to change notification settings - Fork 1
/
GlobalContext.tsx
executable file
·78 lines (69 loc) · 1.76 KB
/
GlobalContext.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import * as React from "react";
import { GlobalFormAction } from "../actions";
import {
GlobalFormState,
GlobalFormDispatch,
ContextChildren,
ContextActions,
FormValues
} from "../types";
const FormState: FormValues = {
amount: 0,
name: ""
};
const InitialGlobalFormState: GlobalFormState = {
form: FormState
};
const FormStateContext = React.createContext<GlobalFormState | undefined>(
undefined
);
const FormDispatchContext = React.createContext<GlobalFormDispatch | undefined>(
undefined
);
export function FormReducer(
state: GlobalFormState,
action: GlobalFormAction
): GlobalFormState {
switch (action.type) {
case ContextActions.SetAmount:
return {
...state,
form: { ...state.form, amount: action.form.amount }
};
case ContextActions.SetName:
return {
...state,
form: { ...state.form, name: action.form.name }
};
default:
return state;
}
}
const FormProvider: ContextChildren = ({ children }) => {
const [state, dispatch] = React.useReducer(
FormReducer,
InitialGlobalFormState
);
return (
<FormStateContext.Provider value={state}>
<FormDispatchContext.Provider value={dispatch}>
{children}
</FormDispatchContext.Provider>
</FormStateContext.Provider>
);
};
function useFormState() {
const context = React.useContext(FormStateContext);
if (context === undefined) {
throw new Error("useFormState must be used within a FormProvider");
}
return context;
}
function useFormDispatch() {
const context = React.useContext(FormDispatchContext);
if (context === undefined) {
throw new Error("useFormDispatch must be used within a FormProvider");
}
return context;
}
export { FormProvider, useFormState, useFormDispatch };