UNPKG

convex

Version:

Client for the Convex Cloud

73 lines (72 loc) 2.44 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 use_subscription_exports = {}; __export(use_subscription_exports, { useSubscription: () => useSubscription }); module.exports = __toCommonJS(use_subscription_exports); var import_react = require("react"); function useSubscription({ // (Synchronously) returns the current value of our subscription. getCurrentValue, // This function is passed an event handler to attach to the subscription. // It should return an unsubscribe function that removes the handler. subscribe }) { const [state, setState] = (0, import_react.useState)(() => ({ getCurrentValue, subscribe, value: getCurrentValue() })); let valueToReturn = state.value; if (state.getCurrentValue !== getCurrentValue || state.subscribe !== subscribe) { valueToReturn = getCurrentValue(); setState({ getCurrentValue, subscribe, value: valueToReturn }); } (0, import_react.useEffect)(() => { let didUnsubscribe = false; const checkForUpdates = () => { if (didUnsubscribe) { return; } setState((prevState) => { if (prevState.getCurrentValue !== getCurrentValue || prevState.subscribe !== subscribe) { return prevState; } const value = getCurrentValue(); if (prevState.value === value) { return prevState; } return { ...prevState, value }; }); }; const unsubscribe = subscribe(checkForUpdates); checkForUpdates(); return () => { didUnsubscribe = true; unsubscribe(); }; }, [getCurrentValue, subscribe]); return valueToReturn; } //# sourceMappingURL=use_subscription.js.map