-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsnippet
48 lines (40 loc) · 1.07 KB
/
snippet
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
import React, { createContext, useReducer } from "react";
type AppState = typeof initialState;
type Action =
| { type: "SET_INPUT_VALUE"; payload: number }
| { type: "SET_INPUT_VALUE_TO_100" };
interface InputProviderProps {
children: React.ReactNode;
}
const initialState = {
inputValue: 0,
};
const reducer = (state: AppState, action: Action) => {
switch (action.type) {
case "SET_INPUT_VALUE":
return {
...state,
inputValue: action.payload,
};
case "SET_INPUT_VALUE_TO_100":
return {
...state,
inputValue: 100,
};
default:
return state;
}
};
const InputValueContext = createContext<{
state: AppState;
dispatch: React.Dispatch<Action>;
}>({ state: initialState, dispatch: () => {} });
function InputValueProvider({ children }: InputProviderProps) {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<InputValueContext.Provider value={{ state, dispatch }}>
{children}
</InputValueContext.Provider>
);
}
export { InputValueContext, InputValueProvider };