1

My state is changing based on incoming props, which then triggers a rebuild of the chart. However, what seems to be happening is that when I mouseover the chart it reveals old data, or data that's disappeared then reappears.

Here's a gif showing the problem: https://i.stack.imgur.com/bMl7s.jpg

And here's my chart code:

  static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.pricesData !== prevState.pricesData) {
      return { pricesData: nextProps.pricesData };
    } else {
      return null;
    }
  }

  componentDidMount() {
    this.buildChart();
  }

  componentDidUpdate(prevProps) {
    if (!_.isEqual(this.props.pricesData, prevProps.pricesData)) {
      this.buildChart();
    }
  }

buildChart fn:

buildChart = () => {
    let datasets = [];
    if (this.state.pricesData) {
      this.state.pricesData.forEach((set) => {
        if (set.titel === "Competiors price") {
          let obj = {};
          obj.label = set.titel;
          obj.backgroundColor = set.color;
          obj.data = [0, set.price];
          obj.tooltip = set.tooltip;
          datasets.push(obj);
        } else {
          let obj = {};
          obj.label = set.titel;
          obj.backgroundColor = set.color;
          obj.data = [set.price, 0];
          obj.tooltip = set.tooltip;
          datasets.push(obj);
        }
      });
    }
    const myChart = new Chart(this.chartRef.current, {
      type: "bar",
      data: {
        labels: ["Change=", "Competitor"],
        datasets: datasets,
      },
      options: {
        legend: {
          display: false,
        },
        title: {
          display: true,
          fontSize: 16,
          text: "Your estimated monthly costs",
        },
        responsive: true,
        maintainAspectRatio: false,
        scales: {
          xAxes: [
            {
              stacked: true,
            },
          ],
          yAxes: [
            {
              stacked: true,
              ticks: {
                callback: function (value) {
                  return "€" + value;
                },
              },
            },
          ],
        },
      },
    });
    this.setState({ chart: myChart });
  };
crevulus
  • 1,658
  • 12
  • 42

0 Answers0