ayanami
Version:
A better way to react with state
43 lines (42 loc) • 1.67 kB
JavaScript
import * as React from 'react';
import identity from 'lodash/identity';
import shallowEqual from 'shallowequal';
export function useSubscribeAyanamiState(ayanami, selector) {
if (selector === void 0) { selector = identity; }
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) {
setState(selector(moduleState));
stateRef.current = selector(moduleState);
}
else {
var before = stateRef.current;
var after = selector(moduleState);
if (!shallowEqual(before, after))
setState(after);
stateRef.current = after;
}
});
}
}
React.useEffect(function () { return function () {
if (subscriptionRef.current) {
subscriptionRef.current.unsubscribe();
}
}; }, [subscriptionRef]);
isFirstRenderRef.current = false;
return state;
}