@yoroi/common
Version:
The Common package of Yoroi SDK
37 lines (36 loc) • 1.97 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.useObservableValue = useObservableValue;
var React = _interopRequireWildcard(require("react"));
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
/**
* For some reason `React.useSyncExternalStore` is not working properly
* **please remember to pass a stable `executor` to avoid re-renderings** e.g `React.useCallback...`
*
* **ATTENTION** useObservableValue was designed to mimic `useSyncExternalStore`
* the executor should read the data from the source and not from the event
* so basically it means -> something changes, please updated with the latest data
*
* **NOTE** if the data from the event is desired to perform some action, please subscribe directly
* and don't use this hook
*
* **NOTE** be mindful that if the observer is a behavior subject, the hook will update twice when mounting
* 1st on the value intialization and
* 2nd after subscribing to the observable (cuz it will emit the last value, when present)
*/
function useObservableValue({
observable$,
getter
}) {
const [value, setValue] = React.useState(getter());
React.useEffect(() => {
const subscription = observable$.subscribe(() => {
setValue(() => getter());
});
return () => subscription.unsubscribe();
}, [getter, observable$]);
return value;
}
//# sourceMappingURL=useObservableValue.js.map