Blog>
Snippets

Dynamic chart updates with GraphQL subscriptions

Explain how to use GraphQL subscriptions to dynamically update TanStack React Charts in real-time as new data becomes available.
import { useSubscription } from '@apollo/client';
import { Chart } from 'react-chartjs-2';
import React, { useState, useEffect } from 'react';

const DATA_SUBSCRIPTION = gql`
  subscription OnNewData {
    newData {
      xValue
      yValue
    }
  }
`;
This code imports necessary libraries and defines a GraphQL subscription that listens for new data.
const DynamicChart = () => {
  const [chartData, setChartData] = useState({
    datasets: [{
      label: 'Live Data',
      data: [],
      backgroundColor: 'rgba(255, 99, 132, 0.6)',
    }],
  });

  const { data, loading } = useSubscription(DATA_SUBSCRIPTION);

  useEffect(() => {
    if (!loading && data) {
      const newPoint = {
        x: data.newData.xValue,
        y: data.newData.yValue,
      };
      setChartData((prevData) => ({
        ...prevData,
        datasets: [{
          ...prevData.datasets[0],
          data: [...prevData.datasets[0].data, newPoint],
        }],
      }));
    }
  }, [data, loading]);

  return <Chart type='line' data={chartData} />;
};
This code defines a React component that uses the subscription to update the chart dynamically. It listens for new data from the subscription, updates the state with the new data point, and re-renders the chart.