UNPKG

@ts-livedata/react

Version:
61 lines (60 loc) 2.15 kB
"use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@ts-livedata/core"); var react_1 = require("react"); /** * React Hook LiveData (similar to {@link MutableLiveData}) which removes observers automatically once unmounted. */ var HookLiveData = /** @class */ (function (_super) { __extends(HookLiveData, _super); function HookLiveData() { return _super !== null && _super.apply(this, arguments) || this; } /** * Attaches and detaches Observer to React functional component. * * @remarks * Should be used within scope of React Hooks, not {@link React.Component}. * Otherwise runtime error will be thrown from React. * * @param observer The observer to watch for changes. */ HookLiveData.prototype.observe = function (observer) { var _this = this; react_1.useEffect(function () { _this.observers.push(observer); var tData = _this.data; if (tData != null) observer(tData); return function () { _this.removeObserver(observer); }; }, []); }; /** * Sets current LiveData value, and notifies observers. * * @param value The value to set. */ HookLiveData.prototype.postValue = function (value) { this.data = value; this.observers.forEach(function (observer) { observer(value); }); }; return HookLiveData; }(core_1.LiveData)); exports.default = HookLiveData;