UNPKG

@designerstrust/remix-utils

Version:

This package contains simple utility functions to use with [Remix.run](https://remix.run).

29 lines (28 loc) 1.14 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useEventSource = void 0; const react_1 = require("react"); /** * Subscribe to an event source and return the latest event. * @param url The URL of the event source to connect to * @param options The options to pass to the EventSource constructor * @returns The last event received from the server */ function useEventSource(url, { event = "message", init } = {}) { const [data, setData] = (0, react_1.useState)(null); (0, react_1.useEffect)(() => { const eventSource = new EventSource(url, init); eventSource.addEventListener(event !== null && event !== void 0 ? event : "message", handler); // rest data if dependencies change setData(null); function handler(event) { setData(event.data || "UNKNOWN_EVENT_DATA"); } return () => { eventSource.removeEventListener(event !== null && event !== void 0 ? event : "message", handler); eventSource.close(); }; }, [url, event, init]); return data; } exports.useEventSource = useEventSource;