stream-hooks
Version:
<div align="center"> <a aria-label="NPM version" href="https://twitter.com/dimitrikennedy"> <img alt="stream-hooks" src="https://img.shields.io/twitter/follow/dimitrikennedy?style=social&labelColor=000000"> </a> <a aria-label="GH Issues" href="h
58 lines (56 loc) • 1.42 kB
JavaScript
"use client"
// src/hooks/use-stream.tsx
import { useCallback, useEffect, useRef } from "react";
function useStream({ onBeforeStart, onStop }) {
const abortControllerRef = useRef(null);
const startStream = async ({
url,
body = {},
headers = {},
method = "POST"
}) => {
try {
const abortController = new AbortController();
abortControllerRef.current = abortController;
onBeforeStart && onBeforeStart();
const response = await fetch(`${url}`, {
method,
headers,
signal: abortController.signal,
...method === "POST" ? { body: JSON.stringify(body) } : {}
});
if (!response.ok || !response?.body) {
throw response;
}
return response?.body;
} catch (err) {
if (err?.name === "AbortError") {
console.log("useStream: stream aborted", err);
abortControllerRef.current = null;
throw err;
}
console.error(`useStream: error`, err);
throw err;
}
};
const stopStream = useCallback(() => {
if (abortControllerRef.current) {
abortControllerRef?.current?.abort();
abortControllerRef.current = null;
}
onStop && onStop();
}, [onStop]);
useEffect(() => {
return () => {
stopStream();
};
}, [stopStream]);
return {
startStream,
stopStream
};
}
export {
useStream
};
//# sourceMappingURL=chunk-5WBUZJKJ.mjs.map