-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
37 lines (30 loc) · 1 KB
/
index.js
File metadata and controls
37 lines (30 loc) · 1 KB
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
/** @format */
import { useContext } from 'react';
import { isArray } from './utils';
const defaultValidation = (val) => val !== undefined;
const checkContext = (context) => {
if (!context.Provider || !context.Consumer) {
throw new Error('getHook was provided a value which is not a context');
}
};
const checkReactVersion = () => {
if (typeof useContext !== 'function') {
throw new Error('You must be using React >= 16.8 to use getHook');
}
};
const createHook = (context, validateFn) => {
checkContext(context);
checkReactVersion();
const value = useContext(context);
if (!validateFn(value)) {
throw new Error('Using a context hook outside of the context provider');
}
return value;
}
export const getHook = (contexts, validateValue = defaultValidation) => () => {
//naive sanity checks that provided context is in fact a context
if(isArray(contexts)){
return contexts.map((context) => createHook(context, validateValue));
}
return createHook(contexts, validateValue);
};