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
@marttp thanks