-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseHandlers.js
45 lines (35 loc) · 1.38 KB
/
useHandlers.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
import { useContext } from 'react';
import { ReduxContext } from '../components/ReduxContext.jsx';
import { isFunction} from '../utils/eq.js';
const defineProp = (o, key, value) => Object.defineProperty(o, key, { value });
const addContextToEvents = props => {
const context = useContext(ReduxContext);
if (!context) return props;
const { eventContext, store } = context;
Object.keys(props).forEach(key => {
let fn;
if (isFunction(fn = props[key])) {
// pin dispatch and the state getter
// to the first parameter, which will more often than not be an event
const usePropsSelectorWrapper = (maybeE, ...rest) => {
if (maybeE?.nativeEvent) {
// todo: make these unwritable
defineProp(maybeE, '$context', eventContext);
defineProp(maybeE, '$dispatch', store.dispatch);
defineProp(maybeE, '$getState', store.getState);
}
return fn(maybeE, ...rest);
};
props[key] = usePropsSelectorWrapper;
}
});
return props;
};
export const useHandlers = (handlers, userProps) => {
const doHook = props => Object.freeze(addContextToEvents({
...handlers,
...props
}));
// curried to allow for composition
return userProps ? doHook(userProps) : doHook;
};