Integrating TanStack Store with WebSocket for Real-time Data
Example to demonstrate integrating TanStack Store with WebSocket to manage and update the application state with real-time data feeds.
import { createStore } from '@tanstack/react-store';
// Define initial state for the store
const initialState = {
messages: []
};
// Create a store with the initial state
const store = createStore({
initialState
});
This code snippet creates a new TanStack Store with an initial state. The initial state contains an empty array for messages, intending to store chat messages received from a WebSocket connection.
const ws = new WebSocket('wss://example.com/ws');
// Listen for messages from the WebSocket connection
globalThis.addEventListener('load', () => {
ws.onmessage = function(event) {
// Parse the incoming message as JSON
const message = JSON.parse(event.data);
// Use the store to update the state with the new message
store.setState((oldState) => ({
messages: [...oldState.messages, message]
}));
};
});
This code snippet sets up a WebSocket connection and listens for incoming messages. When a message is received, it parses the message from JSON and updates the store's state by adding the new message to the messages array.
store.subscribe((state) => {
console.log('New message received', state.messages[state.messages.length - 1]);
});
This code snippet sets up a subscription to the store. Whenever the store's state changes (a new message is received, in this case), it logs the latest message to the console. This could be replaced with any other logic to react to state changes, like updating a UI component.