justHelloWorld
justHelloWorld

Reputation: 6818

Pushing element of an array as part of an object in React

I have this class:

export default class Player {
  constructor() {
    this.scores = [];
  }

 // Insert a new score and keep top N
 insertScore = (score) => {
    this.scores.push(score);
    this.scores.sort((a, b) => b - a);
    if (this.scores.length > N) this.scores.pop();
  };
}

Which is part of a component state:

export default class Menu extends React.PureComponent {
   contructor(props){
     super(props);
     this.state = {
       player: new Player()
     }
   }

   onEndGame(score) {
     player.insertScore(score);
   }
   ...
}

Since changing arrays as part of the state it's very tricky in React (as explained in this aritcle), is the insertScore "legal" in this context?

Upvotes: 2

Views: 808

Answers (1)

Isaac Suarez
Isaac Suarez

Reputation: 84

You are modifying directly a nested property of the state (this.state.player.scores) so it's not correct.

I'll try this:

Player class

insertScore = (score) => {
    this.scores.push(score);
    this.scores.sort((a, b) => b - a);
    if (this.scores.length > N) this.scores.pop();

    return this;
};

Menu class

onEndGame(score) {
    this.setState({
       player: this.state.player.insertScore(score);
    });
}

Upvotes: 1

Related Questions