react >= 18.0.0react-dom >= 18.0.0
npm i -S @benpowley/useStream
Import the hook into the file you want to use it.
import { useStream } from '@benpowley/usestream'Create the call to the hook, passing in the url to call and the type you would like to be returned as an array.
type Todo = {
userId: number
id: number
title: string
completed: boolean
}
const url = 'https://jsonplaceholder.typicode.com/todos'
const { start } = useStream<Todo>({
url,
finished: (data) => {
// Do things with data
},
})The hook can either be destructured as shown above, or can be used directly as below.
const todoStream = useStream<Todo>({
url,
finished: (data) => {
// Do things with data
},
})To start the stream, call the startStream function on the UseStreamReturn type. This is an async function that returns a promise so should be called using async/await.
Destructured:
start()Single Variable:
todoStream.start()const { start, cancel, streaming, sizeDownloaded, timeTaken } = useStream<Todo>({ url })start - function- Starts the streaming functioncancel - function- Cancels the streaming function and any web workersstreaming - boolean- Whether the stream is currently streaming.sizeDownloaded - string- The total amount of data downloaded.