[Solved]React does not re-render after state change

[Solved]React does not re-render after state change


I finished the Freecodecamp Leaderboard challenge but there is a thing bothering me. In the documentation it said that using element.forceUpdate() is not recommended. Without using the forceUpdate() function my element did not re-render even though the state was changed(checked in console.log()). Does React not count reordering of array as a change big enough to re-render or is it somthing else I am doing wrong? This is my code:
Check components/Leaderboard.js

These is my sorting function:
let data = this.state.data;
data.sort((a, b) => b.recent - a.recent);
this.state.data = data;
this.forceUpdate(); // Without this line the elements do not re-render


Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable. https://facebook.github.io/react/docs/react-component.html


this.state.data = data;

is wrong!!!

You should use this.setState({data})


That was it! That was the reason React did not re-render. I changed it to this.setState and now it doesn’t require the forceUpdate(). I saw this in the tutorials but I’m still not used to it and somtimes i forget to use it :slight_smile: Thanks for the help.