UNPKG

llm-hooks

Version:

A collection of useful React hooks for llm-related functionality

33 lines (32 loc) 916 B
import { useState as t, useEffect as E } from "react"; function D(r, a) { const [l, f] = t(""), [i, d] = t(null), [u, o] = t(!1); return E(() => { const n = new AbortController(), w = n.signal; return (async () => { o(!0); try { const e = await fetch(r, { ...a, signal: w }); if (!e.ok) throw new Error(`HTTP error! status: ${e.status}`); const s = e.body?.getReader(); if (!s) throw new Error("No reader available"); const h = new TextDecoder(); let c = ""; for (; ; ) { const { done: b, value: g } = await s.read(); if (b) break; c += h.decode(g, { stream: !0 }), f(c); } } catch (e) { e instanceof Error && d(e); } finally { o(!1); } })(), () => { n.abort(); }; }, [r, a]), { data: l, error: i, loading: u }; } export { D as useFetchStream };