UNPKG

ayanami

Version:
48 lines (47 loc) 1.99 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useSubscribeAyanamiState = void 0; var tslib_1 = require("tslib"); var React = tslib_1.__importStar(require("react")); var identity_1 = tslib_1.__importDefault(require("lodash/identity")); var shallowequal_1 = tslib_1.__importDefault(require("shallowequal")); function useSubscribeAyanamiState(ayanami, selector) { if (selector === void 0) { selector = identity_1.default; } var _a = React.useState(function () { return selector(ayanami.getState()); }), state = _a[0], setState = _a[1]; var ayanamiRef = React.useRef(null); var subscriptionRef = React.useRef(null); var stateRef = React.useRef(state); var isFirstRenderRef = React.useRef(true); if (ayanamiRef.current !== ayanami) { ayanamiRef.current = ayanami; if (subscriptionRef.current) { subscriptionRef.current.unsubscribe(); subscriptionRef.current = null; } if (ayanami) { subscriptionRef.current = ayanami.getState$().subscribe(function (moduleState) { if (isFirstRenderRef.current) return; if (selector === identity_1.default) { setState(selector(moduleState)); stateRef.current = selector(moduleState); } else { var before = stateRef.current; var after = selector(moduleState); if (!shallowequal_1.default(before, after)) setState(after); stateRef.current = after; } }); } } React.useEffect(function () { return function () { if (subscriptionRef.current) { subscriptionRef.current.unsubscribe(); } }; }, [subscriptionRef]); isFirstRenderRef.current = false; return state; } exports.useSubscribeAyanamiState = useSubscribeAyanamiState;