Chartjs-ReactJS ChartJS, data changes when user clicked the button

0πŸ‘

<Bar
  type={"bar"}
  height={120}
  data={dataChart.dataProv} // this state is no mutating no updates/re-renders are stimulated
  options={options}
  plugins={plugins}
  redraw
/>

The data that you are passing to the Bar component is always the same dataChart.dataProv, hence you don’t see the change.

I think you need to create another piece of state that will hold one of the two data properties from the dataChart memo.

My suggestion is to have a state that will hold the name of the property from the memo you want to render in the chart, e.g. dataType this state will hold the values dataProv and dataCity accordingly.

const [dataType, setDataType] = useState('dataProv');

On your click call update its value

const changeData2 = () => {
  setDataType('dataCity');
};

Then in your Bar component use it like this

<Bar
  type={"bar"}
  height={120}
  data={dataChart[dataType]}
  options={options}
  plugins={plugins}
  redraw
/>

Hope that helps.

Leave a comment