Created
March 5, 2024 16:18
-
-
Save lifeisfoo/fbfb344eeab84211424a2094780b18c7 to your computer and use it in GitHub Desktop.
A React SSE client that lists products
This file contains 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
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="UTF-8" /> | |
<title>React SSE example</title> | |
<script src="https://unpkg.com/react@18/umd/react.development.js"></script> | |
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script> | |
<!-- Don't use this in production: --> | |
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script> | |
</head> | |
<body> | |
<div id="root"></div> | |
<script type="text/babel"> | |
function SSEApp() { | |
const [products, setProducts] = React.useState([]); | |
const [listening, setListening] = React.useState(false); | |
React.useEffect(() => { | |
if (!listening) { | |
const events = new EventSource("/events"); | |
events.onmessage = (event) => { | |
// {id: "0123a", name: "my prod", description: "a random product"} | |
const parsedProd = JSON.parse(event.data); | |
setProducts((allProducts) => | |
allProducts.concat(parsedProd) | |
); | |
}; | |
setListening(true); | |
} | |
}, [listening, products]); | |
return ( | |
<table className="stats-table"> | |
<thead> | |
<tr> | |
<th>ID</th> | |
<th>Name</th> | |
<th>Description</th> | |
</tr> | |
</thead> | |
<tbody> | |
{products.map((prod, i) => ( | |
<tr key={prod.id}> | |
<td>{prod.id}</td> | |
<td>{prod.name}</td> | |
<td>{prod.description}</td> | |
</tr> | |
))} | |
</tbody> | |
</table> | |
); | |
} | |
const container = document.getElementById("root"); | |
const root = ReactDOM.createRoot(container); | |
root.render(<SSEApp />); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment