Tuesday, 30 May 2023

Streaming of data not working in React client

I am currently working on a React application the expects a response stream. To simplify the scenario, let's say I have an endpoint that returns a number every second. I am using Flask for this purpose:

def stream():
    def generate():
        import math, time
        for i in range(10):
            yield
            time.sleep(1)

    return generate(), {"Content-Type": "text/plain"}

In my React component, a button click will trigger the following function:

const readStream = () => {
  const xhr = new XMLHttpRequest();
  xhr.seenBytes = 0;
  xhr.open('GET', '/stream', true);
  xhr.onreadystatechange = function(){
    if (this.readyState === 3){
      const data = xhr.response.substr(xhr.seenBytes)
      console.log(data)
      setNumber(data)  // set state value that will be displayed elsewhere
      xhr.seenBytes = xhr.responseText.length;
    }
  }
  xhr.send();
}

For some reason, the React code fails to get the chunks one at a time and it just dumps the data all at once. I've verified that using the same ajax request in vanilla JS works. I've tried different approach as well including using fetch and axios but none worked so far.

Though I am using GET here, my actual use case requires POST and I have to get my data from that response.

Is there anything I am missing out?



from Streaming of data not working in React client

No comments:

Post a Comment