Bug: Fetch API not working correctly when using ReadableStream
See original GitHub issueWhile building a react app, where the front-end must constantly receive streaming data, I noticed that each stream chunk, is only technically received, after the whole stream data is transmitted, although I can chrome network tab that is being received in several chunks. This issue occurs during development, but after building the app for production it no longer occurs.
React version: 16.13.1
Steps To Reproduce
- Create a component that receives a stream of data (for this test a flask stream was used although the bug occurs with other sources )
Code example:
import React, { useEffect } from 'react';
function Page_api() {
useEffect(() => {
const url = '/api/stream'
const consume = responseReader => {
return responseReader.read().then(result => {
if (result.done) { return; }
// do something with the current chunk
const chunk = result.value;
console.log("Received Chunk");
return consume(responseReader);
});
}
fetch(url).then(response => {
return consume(response.body.getReader());
})
.catch(console.log.bind(console));
})
return (
<div>
<p>API Testing Page</p></div>)
}
export default Page_api
Same code in codesandbox: https://codesandbox.io/s/5vtqo , a stream source is also provided as a flask server on the api.py file.
The current behavior
Upon Receiving stream, react can only process each chunk of it on the end of the stream while on development (i.e. using react-scripts start)
The expected behavior
Upon Receiving stream, react can process each chunk as soon as it arrives (i.e. using react-scripts start) - just as it occurs in the built application
Issue Analytics
- State:
- Created 3 years ago
- Comments:5 (1 by maintainers)
After some further testings, it seems it is related to the fact that the client and the flask servers where on the same host, and not related to react at all, thank you all
The problematic code is within
useEffect
. React just runs it and doesn’t affect in any other way. You don’t even call any React-related code (such assetState
) from there. Then again, React doesn’t have any network-related code at all.If you post this question to Stackoverflow, you’d surely get the help you need.