UNPKG

@restate/core

Version:

_Restate_ is a predictable, easy to use, easy to integrate, typesafe state container for [React](https://reactjs.org/).

70 lines (69 loc) 2.58 kB
"use strict"; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __hasOwnProp = Object.prototype.hasOwnProperty; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var create_selector_hook_exports = {}; __export(create_selector_hook_exports, { createSelectorHook: () => createSelectorHook }); module.exports = __toCommonJS(create_selector_hook_exports); var import_react = require("react"); var import_rxjs = require("rxjs"); var import_operators = require("rxjs/operators"); const identitySelectorFunction = (state) => state; function createSelectorHook(context, outerSelector = identitySelectorFunction) { function useAppState(selector, props) { const _store = (0, import_react.useContext)(context); const _props = { deps: [], compare: void 0, ...props }; const state = _store.state; const deps = _props.deps; const startValue = (0, import_react.useMemo)( () => getSelectedValue(state, outerSelector, selector), [...deps] ); const [value, setValue] = (0, import_react.useState)(startValue); const output$ = (0, import_react.useMemo)(() => { return new import_rxjs.BehaviorSubject(startValue); }, [state]); (0, import_react.useEffect)(() => { const stateSub = _store.state$.subscribe((nextStateValue) => { const nextValue = getSelectedValue( nextStateValue.state, outerSelector, selector ); output$.next(nextValue); }); const outputSub = output$.pipe((0, import_operators.distinctUntilChanged)()).subscribe((nextStateValue) => setValue(nextStateValue)); return function cleanup() { stateSub.unsubscribe(); outputSub.unsubscribe(); }; }, [output$, ...deps]); return value; } return useAppState; } function getSelectedValue(state, outerSelector, selector) { const subState = outerSelector(state); const value = selector(subState); return value; }