I’m trying to implement streaming in a React Native application, but I’m encountering issues. Specifically, I’m using the react-native-fetch-api
library along with react-native-polyfill-globals
to make a streaming request, but it doesn’t seem to work as expected.
I’ve read this: Stream api with fetch in a react-native app
Could not get it working. After some debugging, I came up with this:
import 'react-native-polyfill-globals/auto';
import { fetch as fetchh } from 'react-native-fetch-api';
const streamBotResponse = async (conversationId: string, content: string) => {
const response = await fetchh(
`${process.env.EXPO_PUBLIC_API_URL}/api/v1/protected/chats/message/stream/${conversationId}?content=${content}`,
{
headers: {
Authorization: '632133e6-c400-43fe-b4c9-357d05cde8ee',
},
reactNative: { textStreaming: true },
}
);
async function* streamAsyncIterator(stream: ReadableStream) {
const reader = stream.getReader();
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
yield value;
}
} finally {
reader.releaseLock();
}
}
for await (const chunk of streamAsyncIterator(response.body)) {
console.log(new TextDecoder().decode(chunk));
}
};
Can’t seem to resolve: Could not find a declaration file for module ‘react-native-fetch-api’.
Seems to me like this library does not support TypeScript (I could solve the error using a d.ts file but there is not a @types library for react-native-fetch-api (same goes for react-native-polyfill-globals))
But that is not a big problem, I manage to get it to work sort of, but my entire stream response is given back to me in 1 chunk. Is it possible to get it back in multiple smaller chunks? Or is this a limitation of RN and I should just give up on this?