How to read data from the Streams API in React

In this article, we’ll show you how to read data from the Streams API in React. In the previous article, we have explained How to create a streaming API in Node.js using Express.

Demo Application

Output - How to read data from the Streams API in React - Clue Mediator
Output – How to read data from the Streams API in React – Clue Mediator

How to read data from the Streams API in React

  1. Project structure
  2. Package dependencies
  3. Implementation
  4. Output

1. Project structure

  • react-fetch-streams-api
    • node_modules
    • public
      • index.html
    • src
      • App.js
      • index.css
      • index.js
    • package-lock.json
    • package.json
    • README.md

2. Package dependencies

You will find the version of the following packages in React application.

react
^18.2.0

3. Implementation

First, make sure to start the Node.js server to expose the Streams API endpoint at http://localhost:4000. This will allow you to fetch data from the stream using the Fetch API in React.

App.js

In the above example, we use the fetch function to make a request to the stream API endpoint. We then obtain a ReadableStream object from the response and create a reader using the getReader method. We read the stream data in chunks using a while loop and decode each chunk using the TextDecoder. Finally, we update the state with the accumulated data.

4. Output

Run your application and check the output in the browser.
Live Demo

That’s it for today.
Thank you for reading. Happy Coding..!!

Demo & Source Code

GitHub Repository StackBlitz Project
If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *