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
How to read data from the Streams API in React
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
import React, { useState, useEffect } from 'react';
const App = () => {
const [data, setData] = useState('');
const [loading, setLoading] = useState(false);
useEffect(() => {
const fetchData = async () => {
try {
setLoading(true);
const response = await fetch('http://localhost:4000/stream');
if (!response.ok || !response.body) {
throw response.statusText;
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { value, done } = await reader.read();
if (done) {
setLoading(false);
break;
}
const decodedChunk = decoder.decode(value, { stream: true });
setData(prevValue => `${prevValue}${decodedChunk}`);
}
} catch (error) {
setLoading(false);
// Handle other errors
}
};
fetchData();
}, []);
return (
<div>
<h3>How to read data from the Streams API in React - <a href="https://cluemediator.com" target="_blank" rel="noopener">Clue Mediator</a></h3>
<div><b>Request Response: {loading && <i>Fetching data...</i>}</b>{data}</div>
</div>
);
};
export default App;
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..!!