javascript / expert
Snippet
Reactive WebSocket Integration for Streaming Data
Expertly managing asynchronous streams requires bridging imperative protocols like WebSockets with reactive state. Using $state within a class allows for clean encapsulation while ensuring the UI reacts immediately to incoming socket messages.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
class SocketManager {data = $state([]);status = $state('disconnected');connect(url) {const ws = new WebSocket(url);ws.onmessage = (e) => {this.data.push(JSON.parse(e.data));};ws.onopen = () => this.status = 'connected';}}
svelte
Breakdown
1
data = $state([]);
Initializes a reactive array that Svelte will track for mutations.
2
this.data.push(JSON.parse(e.data));
Mutating the proxied array triggers fine-grained updates in the UI.
3
this.status = 'connected';
Updates the connection status reactively.