Blog>
Snippets

Integrating WebSocket for Real-Time Data Visualization

Illustrate the process of fetching real-time data using WebSockets and updating a chart dynamically in a React component with TanStack React Charts.
import React, { useState, useEffect } from 'react';
import { Chart } from 'react-chartjs-2';
import { w3cwebsocket as W3CWebSocket } from 'websocket';

const ChartComponent = () => {
  const [data, setData] = useState([]);

  useEffect(() => {
    const client = new W3CWebSocket('wss://example.com/data');
    client.onmessage = (message) => {
      const newData = JSON.parse(message.data);
      setData(currentData => [...currentData, newData]);
    };

    return () => client.close();
  }, []);

  const options = {
    scales: {
      yAxes: [
        {
          ticks: {
            beginAtZero: true
          }
        }
      ]
    }
  };

  const chartData = {
    labels: data.map(d => d.time),
    datasets: [
      {
        label: 'Real-Time Data',
        data: data.map(d => d.value),
        fill: false,
        backgroundColor: 'rgb(75, 192, 192)',
        borderColor: 'rgba(75, 192, 192, 0.2)',
      },
    ],
  };

  return <Chart type='line' data={chartData} options={options} />;
};

export default ChartComponent;
This code snippet creates a React component (`ChartComponent`) that uses a WebSocket connection to fetch real-time data from a specified URL. It listens for messages from the server, parses the incoming data, and updates the component state with the new data. This updated state is then used to render a line chart using the `react-chartjs-2` library, dynamically displaying the real-time data as it's received. The `useEffect` hook establishes the WebSocket connection and sets up the message handler, while ensuring the connection is closed when the component unmounts to prevent memory leaks.