UNPKG

launch.io

Version:

Launch.IO is an Ultra Hip, Simple, and Fast, Time Traveling React State Management Library

56 lines (55 loc) 2.23 kB
"use strict"; var __read = (this && this.__read) || function (o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.useLaunch = void 0; var react_1 = require("react"); var context_1 = require("../utils/context"); var useContextListener_1 = require("../utils/useContextListener"); /** * A React hook that takes a `selector` function. The selector function receives a context, containing `state` and `actions`, and it should return object containing Launch.IO state and/or actions. * * `const selection = useLaunch({ state, actions} => ({ ... }));` * * `state` is an object that will contain the full application state. * These can be accessed via the name of the service along with the associating state property. * For example, `state.[ServiceName].[ServiceStateProperty]` * * `actions` is an object that will contain the full application launch actions. * These can be accessed via the name of the service along with the associating action. * For example, `actions.[ServiceName].[LaunchAction]` * */ exports.useLaunch = function (selector) { var selectedStateRef = react_1.useRef(); var selectorRef = react_1.useRef(selector); var _a = __read(react_1.useState(function () { return selector(context_1.default.snapshot()); }), 2), selectedState = _a[0], setSelectedState = _a[1]; react_1.useLayoutEffect(function () { selectedStateRef.current = selectedState; selectorRef.current = selector; }); var onContextChange = react_1.useCallback(function (context) { var newState = selectorRef.current(context); if (newState !== selectedStateRef.current) { setSelectedState(newState); } }, []); useContextListener_1.default(onContextChange); return selectedState; };