https://github.com/tauseefk/readable-hook
React hook for wrangling ReadableStream
https://github.com/tauseefk/readable-hook
async iterable react react-hooks readablestream state-management stream typescript
Last synced: about 2 months ago
JSON representation
React hook for wrangling ReadableStream
- Host: GitHub
- URL: https://github.com/tauseefk/readable-hook
- Owner: tauseefk
- License: mit
- Created: 2023-05-22T00:19:54.000Z (about 3 years ago)
- Default Branch: main
- Last Pushed: 2025-06-03T05:10:20.000Z (about 1 year ago)
- Last Synced: 2025-10-10T18:55:54.015Z (8 months ago)
- Topics: async, iterable, react, react-hooks, readablestream, state-management, stream, typescript
- Language: TypeScript
- Homepage: https://www.npmjs.com/package/readable-hook
- Size: 2.19 MB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
## Readable Hook
React hooks for wrangling `ReadableStream`s.
### Installation
```
npm i readable-hook --save
```
### Usage
#### useStreamingQuery
```Typescript
const MyComponent: FC = () => {
const [{ value }, triggerQuery] = useStreamingQuery("path/to/api/endpoint");
return (
{value}
);
};
```
#### useStreamingMutation
Allows synchronizing state with a mutation endpoint that returns a streaming response.
Has a few different ways to pass parameters (at init, and at mutation trigger).
```Typescript
const MyComponent: FC = () => {
const [{ value, isStreaming, done }, triggerMutation] = useStreamingMutation(
"path/to/api/endpoint",
{
// params that can be passed during initialization
},
);
return (
{value}
triggerMutation({
params: {
inputValue: e.target.value,
},
onDone: () => console.log("Done streaming"),
})}
/>
);
};
```
### useReadable
Allows synchronizing state with a `ReadableStream`.
Check [this](https://github.com/tauseefk/readable-hook/blob/main/examples/src/StreamReader.tsx) for a full example.
```Typescript
const MyComponent: FC<{ readableStream: ReadableStream }> = (
{ readableStream },
) => {
const [{ value }, synchronize] = useReadable(async () => readableStream, 100);
return (
{value}
);
};
```
### useIterable
Allows synchronizing state with an async Iterable.
Check [this](https://github.com/tauseefk/readable-hook/blob/main/examples/src/AsyncIterable.tsx) for a full example.
```Typescript
async function* getIntegers() {
let idx = 0;
while (true) {
if (signal?.aborted) {
break;
}
await delay(100);
idx += 1;
yield getCharacters(idx).toString();
}
}
const MyComponent = () => {
const [{ value }, synchronize] = useIterable(
async (_, signal) => getIntegers(signal),
{
accumulate: true,
accumulator: (acc, curr) =>
acc
? `${acc}${curr}`
: `${curr} `,
delay: 100,
},
);
return (
{value}
);
};
```