Sure, let's create a basic Server-Sent Events example using Preact:
First, let's create a simple HTML file:
<!DOCTYPE html>
<html>
<head>
<title>Server Sent Events with Preact</title>
<meta charset="UTF-8">
</head>
<body>
<div id="app"></div>
<script src="https://unpkg.com/preact@10.5.13/dist/preact.min.js"></script>
<script src="app.js"></script>
</body>
</html>
Now, let's create our app.js file which will contain the Preact component:
// Import h and Component from preact
const { h, Component } = preact;
// Our App component that will manage Server-Sent Events
class App extends Component {
constructor() {
super();
// Set an initial state containing an empty "messages" array
this.state = {
messages: []
};
}
// Lifecycle method to start listening to events when the component gets mounted
componentDidMount() {
// Create a new EventSource to establish a connection with the SSE stream
this.eventSource = new EventSource("path/to/sse/server");
// Set a callback to handle incoming message events
this.eventSource.onmessage = (event) => {
// Parse the event data as JSON
const newMessage = JSON.parse(event.data);
// Append the new message to the current list of messages in the state
this.setState({
messages: [...this.state.messages, newMessage]
});
};
}
// Lifecycle method to clean up the event source when a component is unmounted
componentWillUnmount() {
this.eventSource.close();
}
render() {
const { messages } = this.state;
return (
// Display the list of messages
<ul>
{messages.map((message, index) => (
<li key={index}>{message.text}</li>
))}
</ul>
);
}
}
// Render the App component
preact.render(h(App), document.getElementById("app"));
Now let's go line-by-line inside app.js:
- Import the required functions from Preact:
h and Component. h is used for creating elements and Component is used for creating a custom Preact component;
- Create the
App class extending the Component class;
- Use the
constructor function to initialize the component's state with an empty array messages;
componentDidMount is a lifecycle method that is called after a component is mounted. Here, we create an EventSource object to connect to the server;
- Set a callback for handling incoming message events using
this.eventSource.onmessage;
- Parse the incoming data from the event and append the message to the current list of messages in the state;
- Use the
componentWillUnmount lifecycle method to close the connection when the component is unmounted;
- Use the
render method to render the list of messages received from the server;
- Finally, render the
App component and attach it to the DOM.
The example assumes that you have a working Server-Sent Events server at "path/to/sse/server". Make sure to replace this URL with your actual server URL.
To see the Server-Sent Events in action, open the HTML file in a modern web browser, and you should see the messages received from the server updating the list in real-time.