JSFiddle - React, Tailwind, and code Playground

by AshThakur

HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Dynamic Chart Update</title>
  <!-- Include Chart.js library -->
  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
  <!-- Create a canvas element to render the chart -->
  <canvas id="myChart" width="400" height="200"></canvas>

  <script>
    // Sample initial data
    const initialData = {
      labels: ['January', 'February', 'March', 'April', 'May'],
      datasets: [{
        label: 'Sample Data',
        backgroundColor: 'rgba(75, 192, 192, 0.2)',
        borderColor: 'rgba(75, 192, 192, 1)',
        borderWidth: 1,
        data: [65, 59, 80, 81, 56],
      }],
    };

    // Get the canvas element
    const ctx = document.getElementById('myChart').getContext('2d');

    // Create a new chart instance
    const myChart = new Chart(ctx, {
      type: 'bar',
      data: initialData,
    });

    // Function to update chart data
    function updateChartData(newData) {
      myChart.data = newData;
      myChart.update();
    }

    // Example: Update chart data after a delay
    setTimeout(() => {
      const newData = {
        labels: ['June', 'July', 'August', 'September', 'October'],
        datasets: [{
          label: 'Updated Data',
          backgroundColor: 'rgba(255, 99, 132, 0.2)',
          borderColor: 'rgba(255, 99, 132, 1)',
          borderWidth: 1,
          data: [45, 32, 70, 45, 80],
        }],
      };

      updateChartData(newData);
    }, 3000); // Update data after 3 seconds
    
    
    
     setTimeout(() => {
      const newData = {
        labels: ['June', 'July', 'August', 'September', 'October'],
        datasets: [{
          label: 'Updated Data',
          backgroundColor: 'rgba(0, 0, 0, 0.2)',
          borderColor: 'rgba(0, 0, 0, 1)',
          borderWidth: 1,
          data: [40, 33, 44, 475, 44],
        }],
      };

     ...