UNPKG

@helenejs/react

Version:

Real-time Web Apps for Node.js

37 lines 1.44 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.useTracker = useTracker; const react_1 = require("react"); const data_1 = require("@helenejs/data"); const isEmpty_1 = __importDefault(require("lodash/isEmpty")); const lodash_1 = require("lodash"); function useTracker(func, collections, deps = []) { const [data, setData] = (0, react_1.useState)(null); (0, react_1.useEffect)(() => { if ((0, isEmpty_1.default)(collections)) { throw new Error('collection deps is required'); } const onUpdated = (0, lodash_1.throttle)(() => { func().then(setData).catch(console.error); }, 20, { leading: true, trailing: true, }); onUpdated(); for (const collection of collections) { collection.on(data_1.CollectionEvent.READY, onUpdated); collection.on(data_1.CollectionEvent.UPDATED, onUpdated); } return () => { for (const collection of collections) { collection.off(data_1.CollectionEvent.READY, onUpdated); collection.off(data_1.CollectionEvent.UPDATED, onUpdated); } }; }, [...collections, ...deps]); return data; } //# sourceMappingURL=use-tracker.js.map