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 (54 loc) • 2.28 kB
JavaScript
;Object.defineProperty(exports, "__esModule", {value: true}); function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }"use client"
// src/hooks/use-stream.tsx
var _react = require('react');
function useStream({ onBeforeStart, onStop }) {
const abortControllerRef = _react.useRef.call(void 0, 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 || !_optionalChain([response, 'optionalAccess', _ => _.body])) {
throw response;
}
return _optionalChain([response, 'optionalAccess', _2 => _2.body]);
} catch (err) {
if (_optionalChain([err, 'optionalAccess', _3 => _3.name]) === "AbortError") {
console.log("useStream: stream aborted", err);
abortControllerRef.current = null;
throw err;
}
console.error(`useStream: error`, err);
throw err;
}
};
const stopStream = _react.useCallback.call(void 0, () => {
if (abortControllerRef.current) {
_optionalChain([abortControllerRef, 'optionalAccess', _4 => _4.current, 'optionalAccess', _5 => _5.abort, 'call', _6 => _6()]);
abortControllerRef.current = null;
}
onStop && onStop();
}, [onStop]);
_react.useEffect.call(void 0, () => {
return () => {
stopStream();
};
}, [stopStream]);
return {
startStream,
stopStream
};
}
exports.useStream = useStream;
//# sourceMappingURL=chunk-VBU466HQ.js.map