Info |
---|
The code demonstrates how to consume an SSE stream in a ReactJS application. |
Setup for Python
Install Python - https://www.python.org/downloads/
Using the command line install the following python packages
Code Block |
---|
pip install flask
pip install flask_cors |
Unarchive the following
View file | ||
---|---|---|
|
to a unique location on your machine (somewhere where it’s easy to find)
From the command line navigate to the folder where you have extracted this archive, and run the following command
Code Block |
---|
python webServiceStream.py |
Observe the output, it should conclude with a message saying Running on http://0.0.0.0:8080/ (Press CTRL+C to quit)
Using your browser, enter the URL http://localhost:8080, you should see the message “Data Generator is running…”
Change the URL to http://localhost:8080/streamTest/, you should now see a stream of data (this is not a HTML5 SSE stream).
Change the URL to http://localhost:8080/streamTest/sse/, you should now see a stream of data (this is a HTML5 SSE stream).
You are now ready to connect your React or Angular view to the stream.
Setup for React
install Node.js - https://nodejs.org/en/download/
Using the command line install the following React packages
Code Block |
---|
npm install rxjs
npm install rxjs-hooks |
Running the application
Use the command and create a new react application
Code Block |
---|
npx create-react-app <directory> |
Open the project in your IDE
Replace the code in App.js with the code below
Note: The endpointUrls.dockerurlwindowsvbpythonStream should be replaced with the URL for your own SSE stream of data.
Code Block | ||
---|---|---|
| ||
import React, { useState } from 'react'; import { useObservable } from 'rxjs-hooks'; import { Observable } from 'rxjs'; import { map, withLatestFrom } from 'rxjs/operators'; import { endpointUrls } from './config'; const stringObservable = Observable.create(observer => { const source = new EventSource(endpointUrls.dockerurlwindowsvbpythonStream); source.addEventListener('message', (messageEvent) => { console.log(messageEvent); observer.next(messageEvent.data); }, false); }); function App() { const [stringArray, setStringArray] = useState([]); useObservable( state => stringObservable.pipe( withLatestFrom(state), map(([state]) => { let updatedStringArray = stringArray; updatedStringArray.unshift(state); if (updatedStringArray.length >= 50) { updatedStringArray.pop(); } setStringArray(updatedStringArray); return state; }) ) ); return ( <> {stringArray ? stringArray.map((message, index) => <p key={index}>{message}</p>) : <p>Loading...</p>} </> ); } export default App; |
Create a config.jsx file and add the code below into it. Setting the pythonStream field to the URL that the python application is streaming the HTML5 SSE data on.
config.jsx
Code Block |
---|
export const endpointUrls = {
pythonStream: 'http://localhost:8080/streamTest/sse'
} |
Run your React application with
Code Block |
---|
npm start |