@ohm-vision/react-async
Version:
Extentions to React to support asynchronous calls
86 lines (85 loc) • 3.3 kB
JavaScript
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
import { useEffect, useRef, useState } from "react";
export function useEventSource(_a, deps) {
var url = _a.url, withCredentials = _a.withCredentials, handlers = __rest(_a, ["url", "withCredentials"]);
var _b = useState([]), events = _b[0], setEvents = _b[1];
var handlerRef = useRef(handlers);
useEffect(function () {
var _a = handlerRef.current, open = _a.open, error = _a.error, message = __rest(_a, ["open", "error"]);
var messages = Object.entries(message).reduce(function (curr, _a) {
var key = _a[0], value = _a[1];
curr[key] = function (_a) {
var type = _a.type, dataStr = _a.data, lastEventId = _a.lastEventId, ports = _a.ports, source = _a.source, bubbles = _a.bubbles, cancelable = _a.cancelable, composed = _a.composed;
var data;
try {
data = JSON.parse(dataStr);
}
catch (_b) {
data = dataStr;
}
var event = new MessageEvent(type, {
data: data,
lastEventId: lastEventId,
origin: origin,
ports: ports ? __spreadArray([], ports, true) : undefined,
source: source,
bubbles: bubbles,
cancelable: cancelable,
composed: composed
});
onMessage(event);
};
return curr;
}, {
open: onOpen,
error: onError
});
var source = new EventSource(url, {
withCredentials: withCredentials
});
function onOpen(e) {
setEvents([]);
if (open) {
open(e);
}
}
function onError(e) {
stopAndClose();
if (error) {
error(e);
}
}
function onMessage(e) {
// append the event
setEvents(function (events) { return __spreadArray(__spreadArray([], events, true), [
e
], false); });
}
function stopAndClose() {
if (source.readyState !== EventSource.CLOSED) {
source.close();
}
}
return stopAndClose;
}, __spreadArray([url, withCredentials, handlerRef], deps, true));
return events;
}