How to consume server sent events in React
Let's learn how to consume a server sent events in React in this article, we will use the same example from the previous article.
import React, { useEffect, useState } from 'react'
const App = () => {
const [score, setScore] = useState({})
useEffect(() => {
// Create a new EventSource
const eventSource = new EventSource('http://localhost:3000/scores')
// Listen to the message event
eventSource.onmessage = (event) => {
const data = JSON.parse(event.data)
setScore(data)
}
return () => {
// close the server connection
eventSource.close()
}
}, [])
return (
<div>
<h2>Live Football Scores</h2>
<p>Team: {score.team}</p>
<p>Goals: {score.goals}</p>
<p>Possession: {score.possession}</p>
</div>
)
}
Here we just created a new EventSource object and passed the URL of the server sent events endpoint. Then we listened to the message event and parsed the data. We also closed the connection when the component unmounts.
How event source works?
EventSource is a keep-alive connection between the client and the server. The server can send data to the client without the client requesting it. We will see about event source in other article.
Hope you learnt on how to consume server sent events in React. Thanks for reading, happy coding š
If you want to learn how to send the data using SSE in node Js, You can check our previous article how to send server sent events in Node.js.