-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseSaveableState.ts
73 lines (55 loc) · 1.53 KB
/
useSaveableState.ts
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
import { useReducer, useCallback } from "react";
type SetState<T> = (newPresent: T) => void;
interface IActions<T> {
type: ActionTypes;
newState?: T;
}
interface State<T> {
state: T;
canSave: boolean
}
enum ActionTypes {
SET = "SET",
SAVE = "SAVE",
}
const initialState = {
state: null,
canSave: false,
};
function useSaveableState<T>(initialPresent: T, onSave?: (newState: T) => void): [T, SetState<T>, {saveState: () => void, canSave: boolean}] {
const reducer = useCallback((state: State<T>, action: IActions<T>):State<T> => {
const { state: prevState } = state;
const { newState } = action;
switch (action.type) {
case ActionTypes.SET: {
if (newState === prevState) {
return state;
}
return {
state: newState!,
canSave: true,
};
}
case ActionTypes.SAVE: {
if (onSave) {
onSave(state.state);
}
return {
state: state.state,
canSave: false,
};
}
default:
return state;
}
}, []);
const [stateObj, dispatch] = useReducer<(state: State<T>, action: IActions<T>) => State<T>>(reducer, {
...initialState,
state: initialPresent,
});
const setState = useCallback((newState) => dispatch({ type: ActionTypes.SET, newState }), []);
const saveState = useCallback(() => dispatch({ type: ActionTypes.SAVE }), []);
const canSave = stateObj.canSave;
return [stateObj.state, setState, {saveState, canSave}];
}
export default useSaveableState;