Chartjs-Replace Chart.js Data during `onClick` causes _meta error

1👍

You can do the trick by using setTimeout in your click handler:

onClick: () => {
    setTimeout(drilldownIntoRed);
},

Check it out:

const labelsA = ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"];
const datasetA = [{
    y: 12,
    x: "Red"
  },
  {
    y: 19,
    x: "Blue"
  },
  {
    y: 3,
    x: "Yellow"
  },
  {
    y: 5,
    x: "Green"
  },
  {
    y: 2,
    x: "Purple"
  },
  {
    y: 3,
    x: "Orange"
  }
];

const labelsADrilldown = ["Fav", "Like it", "Just OK"];
const datasetADrilldown = [{
    y: 3,
    x: "Fav Color"
  },
  {
    y: 7,
    x: "Like it"
  },
  {
    y: 2,
    x: "Just OK"
  },
]

const labelsB = ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"];
const datasetB = [{
    y: 2,
    x: "Red"
  },
  {
    y: 7,
    x: "Blue"
  },
  {
    y: 4,
    x: "Yellow"
  },
  {
    y: 12,
    x: "Green"
  },
  {
    y: 1,
    x: "Purple"
  },
  {
    y: 8,
    x: "Orange"
  }
];

let mychart = null;

function go() {
  const ctx = document.getElementById("myChart").getContext("2d");
  myChart = new Chart(ctx, {
    type: "bar",
    data: {
      labels: labelsA,
      datasets: [{
          label: "Bear Votes",
          data: datasetA,
          backgroundColor: "rgba(255, 29, 255, 0.5)"
        },
        {
          label: "Turtle Votes",
          data: datasetB,
          backgroundColor: "rgba(255, 99, 55, 0.5)"
        }
      ]
    },
    options: {
      onClick: () => {
        setTimeout(drilldownIntoRed);
      },
      scales: {
        xAxes: [{
          stacked: true
        }],
        yAxes: [{
          stacked: true
        }]
      }
    }
  });
}

function drilldownIntoRed() {
  myChart.data = {
    labels: labelsADrilldown,
    datasets: [{
      label: "# of Votes",
      data: datasetADrilldown,
      backgroundColor: "rgba(255, 29, 255, 0.5)"
    }]
  };

  myChart.update(0);
}

function reset() {
  if (myChart) {
    myChart.destroy();
  }
  go();
}

document.addEventListener("DOMContentLoaded", go);
document.getElementById("reset").addEventListener("click", reset);
.hint {
  font-style: italic;
  font-family: "Whitney SSm A", "Whitney SSm B", Helvetica, Arial, sans-serif;
  font-size: .75rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.js" integrity="sha512-QEiC894KVkN9Tsoi6+mKf8HaCLJvyA6QIRzY5KrfINXYuP9NxdIkRQhGq3BZi0J4I7V5SidGM3XUQ5wFiMDuWg==" crossorigin="anonymous"></script>

<div style="width:300px;height: 300px">
  <canvas id="myChart" width="100px" height="100px"></canvas>
</div>
<p class="hint">Click a bar to drill down</p>
<button id="reset">Reset</button>

Leave a comment