-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
66 lines (54 loc) · 1.63 KB
/
index.js
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
import { useReducer, useEffect, useRef } from 'react';
const PATCH = '@action_types/PATCH';
const DERIVE = '@action_types/DERIVE';
const noop = () => {};
const isObject = (arg) => {
return arg === Object(arg) && !Array.isArray(arg);
};
const reducer = (state, action) => {
switch ( action.type ) {
case PATCH:
return {
...state,
...action.payload,
};
case DERIVE:
return {
...state,
...action.updater(state),
};
default: console.error(`Unexpected action type: ${action.type}`); return state;
}
};
const useSetState = (initState) => {
if ( !isObject(initState) && initState !== null ) {
throw Error(
'Invalid argument type passed to useSetState. Initial state must be an object or null.'
);
}
const [_state, _dispatch] = useReducer(reducer, initState);
const _patchState = update => _dispatch({ type: PATCH, payload: update });
const _deriveState = updater => _dispatch({ type: DERIVE, updater });
const _setStateCallback = useRef();
useEffect(() => {
if ( typeof _setStateCallback.current === 'function' ) {
_setStateCallback.current();
}
_setStateCallback.current = noop;
}, [_state]);
const setState = (arg, callback = noop) => {
_setStateCallback.current = callback;
if ( typeof arg === 'function' ) {
_deriveState(arg);
} else if ( isObject(arg) ) {
_patchState(arg);
} else {
throw Error(
'Invalid argument type passed to setState. Argument must either be a plain object or' +
'an updater function.'
);
}
};
return [_state, setState];
};
export default useSetState;