Streaming
Nitro Fetch can expose a streaming mode that returns a ReadableStream body. Combined with react-native-nitro-text-decoder, you can incrementally decode UTF-8 chunks.
Installation
Make sure you have the text decoder package installed:
npm i react-native-nitro-text-decoder
Usage
import { useRef, useState } from 'react';
import { fetch as nitroFetch } from 'react-native-nitro-fetch';
import { TextDecoder } from 'react-native-nitro-text-decoder';
export function StreamingExample() {
const [output, setOutput] = useState('');
const decoder = useRef(new TextDecoder());
const append = (text: string) => {
setOutput((prev) => prev + text);
};
const runStream = async () => {
// `stream: true` enables the streaming transport
const res = await nitroFetch('https://httpbin.org/stream/20', {
stream: true,
});
const reader = res.body?.getReader();
if (!reader) {
append('No readable stream!');
return;
}
let chunks = 0;
while (true) {
const { done, value } = await reader.read();
if (done) break;
chunks++;
const text = decoder.current.decode(value, { stream: true });
append(text);
}
append(`\n\nDone - ${chunks} chunk(s) received`);
};
// Call `runStream()` from a button handler in your UI
}
tip
Pass { stream: true } in the fetch options to enable streaming mode. Without it, the full body is buffered before resolving.
How it works
fetch()withstream: truereturns aResponsewhosebodyis aReadableStream<Uint8Array>- Use
getReader()to obtain aReadableStreamDefaultReader - Call
reader.read()in a loop untildoneistrue - Decode each
Uint8Arraychunk withTextDecoderfor UTF-8 text
Streaming is supported on both Android and iOS.