Created
February 9, 2020 05:06
-
-
Save marttp/5bdfa30acfc44b24ff3262893d61e4ca to your computer and use it in GitHub Desktop.
Example of Server-Sent Events in Client (React)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState } from "react"; | |
import axios from 'axios'; | |
import "./App.css"; | |
export default function App() { | |
const [process, setProcess] = useState({}); | |
const [message, setMessage] = useState({}); | |
const [listening, setListening] = useState(false); | |
const statusMessage = { | |
subscribed: "Subscribed", | |
unsubscribed: "Unsubscribed" | |
}; | |
const subscribe = async () => { | |
const status = listening; | |
if (!status) { | |
const events = new EventSource("http://localhost:8000/events"); | |
events.onmessage = event => { | |
const parsedData = JSON.parse(event.data); | |
console.log(event) | |
switch (parsedData.type) { | |
case "init-connection": | |
setProcess(parsedData.processId); | |
break; | |
case "message": | |
setMessage(parsedData.message); | |
break; | |
} | |
}; | |
} else { | |
setProcess({}); | |
setMessage({}); | |
await axios.delete(`http://localhost:8000/closes/${process}`) | |
} | |
setListening(!listening); | |
}; | |
return ( | |
<div> | |
<p>{listening ? statusMessage.subscribed : statusMessage.unsubscribed}</p> | |
<p>{JSON.stringify(process)}</p> | |
<button onClick={subscribe}> | |
{listening ? statusMessage.unsubscribed : statusMessage.subscribed} | |
</button> | |
<br /> | |
<p>{JSON.stringify(message)}</p> | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@saujanya01 Hi.
Actually, this is quite old gist but this is reflected in the server-sent event.
The
EventSource
refers to opening the traffic between client-server.SSE (Server-Sent Event) is the methodology to use the backend to send the data to the frontend but in unidirection.
That's mean, only server can send the data to client via the process which client open the tunnel to them.
If you prefer to open communication in bidirections, the options is would be
If you prefer stream, then maybe prefer to use kind of POST RESTful endpoint, and the logic behind server, publish the asynchronous message to use another stream process e.g. KafkaStream, and etc.