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

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

#1

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:
sortByRecent(){
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
}


#2

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:

this.state.data = data;

is wrong!!!

You should use this.setState({data})


#3

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.