Chartjs-How to save the previous state and current state for a barchart in reactjs

2👍

Error explains it, you are trying to access a constant before you initialize it. const current = series; is after const prev = current;.

But the problem is you are trying to render the previous values without storing them in state. What if your component re-renders? The previous data will be lost.

You want to keep the previous values in state:

state = {
    analysis: {
        tonal: [],
    },
    prevAnalysis: {
        tonal: [],
    },
    showButton: false,
};

Update when you receive new data:

const currAnalysis = // clone this.state.analysis

this.setState({
    prevAnalysis: currAnalysis,
    analysis: { ...this.state.analysis, tonal: tonalArray },
    showButton: true
});

Then use the prevAnalysis in your component as prev. You don’t need this

const prev = current;
const current = series;  

Generally, everything that is not saved in state will be used for the current render, whenever you want to keep previous values etc. in memory, you store them in state.

0👍

You have error in your code here:

render() {
    const series = this.state.analysis.tonal.map((tonal) => tonal.value);
    const prev=current;
    const current = series; //error here

Your code trying to access value current, and after that you are declaring it using const.

Leave a comment