/
index.js
39 lines (29 loc) · 1021 Bytes
/
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
import React from 'react';
const composeHooks = hooks => Component => {
if (!Component) {
throw new Error('Component must be provided to compose');
}
if (!hooks) {
return Component;
}
return props => {
const hooksObject = typeof hooks === 'function' ? hooks(props) : hooks;
// Flatten values from all hooks to a single object
const hooksProps = Object.entries(hooksObject).reduce((acc, [hookKey, hook]) => {
let hookValue = hook();
if (Array.isArray(hookValue) || typeof hookValue !== 'object') {
hookValue = { [hookKey]: hookValue };
}
Object.entries(hookValue).forEach(([key, value]) => {
const duplicate = acc[key] ? value : props[key];
if (typeof duplicate !== 'undefined') {
console.warn(`prop '${key}' exists, overriding with value: '${duplicate}'`);
}
acc[key] = value;
});
return acc;
}, {});
return <Component {...hooksProps} {...props} />;
};
};
export default composeHooks;