@react-nano/use-event-source
Version:
A lightweight EventSource (server-sent-events) hook for react, written in TypeScript
31 lines (30 loc) • 1.18 kB
JavaScript
import { useEffect, useRef, useState } from "react";
export function useEventSource(url, withCredentials, ESClass = EventSource) {
const source = useRef(null);
const [status, setStatus] = useState("init");
useEffect(() => {
if (url) {
const es = new ESClass(url, { withCredentials });
source.current = es;
es.addEventListener("open", () => setStatus("open"));
es.addEventListener("error", () => setStatus("error"));
return () => {
source.current = null;
es.close();
};
}
setStatus("closed");
return undefined;
}, [url, withCredentials, ESClass]);
return [source.current, status];
}
export function useEventSourceListener(source, types, listener, dependencies = []) {
useEffect(() => {
if (source) {
types.forEach((type) => source.addEventListener(type, listener));
return () => types.forEach((type) => source.removeEventListener(type, listener));
}
return undefined;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [source, ...dependencies]);
}