[Chartjs]-Functional component not re-rendering after setState update hook

9👍

The reason why your component doesn’t re-render is because you’re directly mutating your state when you use data.sort and according to React docs, you should

Never mutate state directly, as calling setState() afterwards may replace the mutation you made. Treat state as if it were immutable.

Since Array.sort method is mutable, you should create a copy of data and then use Array.sort on the new array.

const Landing = () => {
  const [data, setData] = React.useState([
    { year: 2017, value: 50 },
    { year: 2016, value: 60 },
    { year: 2013, value: 50 },
    { year: 2014, value: 80 },
    { year: 2019, value: 70 }
  ]);

  const sortData = () => {
    // using `spread operator` to create
    // a copy of the `data` array
    const newArray = [...data].sort(function(a, b) {
      return a.year - b.year;
    });
    setData(newArray);
  };

  return (
    <div>
      <BarChart data={data} />
      <button onClick={sortData}> sort data </button>
    </div>
  );
};

If an array method mutates the original array, always make a copy of your array before updating your state.

Have a look here to see which Array methods are mutable and which ones are not:

Leave a comment