-
Notifications
You must be signed in to change notification settings - Fork 106
/
Copy pathstore.js
38 lines (35 loc) · 1.35 KB
/
store.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
import { useMemo } from 'react';
import { observable } from '@nx-js/observer-util';
import { batchMethods } from './batch';
import {
isInsideFunctionComponent,
isInsideClassComponentRender,
isInsideFunctionComponentWithoutHooks,
} from './view';
function createStore(obj) {
return batchMethods(
observable(typeof obj === 'function' ? obj() : obj),
);
}
export function store(obj) {
// do not create new versions of the store on every render
// if it is a local store in a function component
// create a memoized store at the first call instead
if (isInsideFunctionComponent) {
// useMemo is not a semantic guarantee
// In the future, React may choose to “forget” some previously memoized values and recalculate them on next render
// see this docs for more explanation: https://reactjs.org/docs/hooks-reference.html#usememo
return useMemo(() => createStore(obj), []);
}
if (isInsideFunctionComponentWithoutHooks) {
throw new Error(
'You cannot use state inside a function component with a pre-hooks version of React. Please update your React version to at least v16.8.0 to use this feature.',
);
}
if (isInsideClassComponentRender) {
throw new Error(
'You cannot use state inside a render of a class component. Please create your store outside of the render function.',
);
}
return createStore(obj);
}