Blog>
Snippets

Real-time Data Updates with WebSockets

Exemplify how `createReducer` can be used to handle real-time data updates in a stock market dashboard using WebSocket connections.
import { configureStore, createSlice } from '@reduxjs/toolkit';

// Define the initial state of the stocks slice
const initialState = {
    stocks: {}
};

// Create a slice for the stocks with the reducers to handle the actions
const stocksSlice = createSlice({
    name: 'stocks',
    initialState,
    reducers: {
        // Reducer to handle stock updates
        stockUpdated(state, action) {
            const { symbol, price } = action.payload;
            state.stocks[symbol] = price;
        }
    }
});

// Destructure and export the action
export const { stockUpdated } = stocksSlice.actions;

// Create a Redux store with the slice reducer
const store = configureStore({
    reducer: {
        stocks: stocksSlice.reducer
    }
});

export default store;
This code creates a Redux slice for stocks with an initial state and a reducer to handle stock updates. It then exports the action and configures a Redux store with the slice reducer.
import { stockUpdated } from './store';

// Establish a WebSocket connection
const socket = new WebSocket('wss://example.com/stocks');

// Listen for messages on the WebSocket
socket.onmessage = (event) => {
    // Parse the incoming message as JSON
    const data = JSON.parse(event.data);

    // Assume data is an array of stock objects with 'symbol' and 'price'
    data.forEach(stock => {
        // Dispatch the 'stockUpdated' action to update the store with the new price
        store.dispatch(stockUpdated(stock));
    });
};
This code establishes a WebSocket connection to a stock market data feed, listens for messages, parses them as JSON, and dispatches the corresponding actions to the Redux store to update the stock prices in real-time.