Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

React state change is puzzling

I used a map function on an array that is part of the state, since map does not change the original array but it seems to be affecting it ?

Here is the code : ``

import Player from './Player'; import Header from './Header'; import AddPlayerForm from './AddPlayerForm';

class App extends Component { state = { players: [ { name: "Guil", score: 0, id: 1, isHigh: true }, { name: "Treasure", score: 0, id: 2, isHigh: false

  },
  {
    name: "Ashley",
    score: 0,
    id: 3,
    isHigh: false
  },
  {
    name: "James",
    score: 0,
    id: 4,
    isHigh: false
  }
]

}; // player id counter prevPlayerId = 4;

handleScoreChange = (index, delta) => { this.setState( (prevState) => ({ score: prevState.players[index].score += delta }));

}

FindHighScore = () => { //console.log(ind);

const maxScore = this.state.players.reduce((total, player) =>{
  //console.log(player.score);
  if (total > player.score) {
    return total;

  } else {
    return player.score;
  }
}, 0)
console.log(maxScore);
let highest = this.state.players.map((player)=>{
  if (player.score === maxScore) {
    return player.isHigh = true;
  } else {
      return player.isHigh = false;
  }
})
console.log(highest);

}

handleAddPlayer = (name) => {

this.setState( (prevState)=> { return { players: [ ...prevState.players, { name: name, score: 0, id: this.prevPlayerId += 1 } ] } })

} handleRemovePlayer = (id) => { this.setState( prevState => { return { players: prevState.players.filter((p) => p.id !== id) }; }); }

render() { //props = {tile: "Scoreboard", Players: [{name: "Guil", scoe: 0, id: 0}]} this.FindHighScore(); return ( <div className="scoreboard"> <Header players={this.state.players} />

    {/* Players list */}
    {this.state.players.map( (player, index) =>
      <Player 
        name={player.name}
        score = {player.score}
        id={player.id}
        key={player.id.toString()} 
        index = {index}
        changeScore = {this.handleScoreChange}
        removePlayer={this.handleRemovePlayer}  
        highScore ={player.isHigh}         
      />
    )}
    <AddPlayerForm addPlayer ={this.handleAddPlayer}/>
  </div>
);

} }

export default App;

`` I call the function this.FindHighScore(); before the rendering takes place, which is updating the state ?

1 Answer

Sorry here is the code

import Player from './Player';
import Header from './Header';
import AddPlayerForm from './AddPlayerForm';



class App extends Component {
  state = {
    players: [
      {
        name: "Guil",
        score: 0,
        id: 1,
        isHigh: true
      },
      {
        name: "Treasure",
        score: 0,
        id: 2,
        isHigh: false

      },
      {
        name: "Ashley",
        score: 0,
        id: 3,
        isHigh: false
      },
      {
        name: "James",
        score: 0,
        id: 4,
        isHigh: false
      }
    ]
  };
// player id counter
  prevPlayerId = 4;


  handleScoreChange = (index, delta) => {
    this.setState( (prevState) => ({
      score: prevState.players[index].score += delta
    }));


  }

  FindHighScore = () => {
    //console.log(ind);

    const maxScore = this.state.players.reduce((total, player) =>{
      //console.log(player.score);
      if (total > player.score) {
        return total;

      } else {
        return player.score;
      }
    }, 0)
    console.log(maxScore);
    let highest = this.state.players.map((player)=>{
      if (player.score === maxScore) {
        return player.isHigh = true;
      } else {
          return player.isHigh = false;
      }
    })
    console.log(highest);
  }



  handleAddPlayer = (name) => {

   this.setState( (prevState)=> {
     return {
        players: [
          ...prevState.players,
          {
            name: name,
            score: 0,
            id: this.prevPlayerId += 1
          }
        ]
        }
   })

  }
  handleRemovePlayer = (id) => {
    this.setState( prevState => {
      return {
        players: prevState.players.filter((p) => p.id !== id)
      };
    });
  }


  render() {
     //props = {tile: "Scoreboard", Players: [{name: "Guil", scoe: 0, id: 0}]}
     this.FindHighScore();
    return (
      <div className="scoreboard">
        <Header players={this.state.players} />

        {/* Players list */}
        {this.state.players.map( (player, index) =>
          <Player 
            name={player.name}
            score = {player.score}
            id={player.id}
            key={player.id.toString()} 
            index = {index}
            changeScore = {this.handleScoreChange}
            removePlayer={this.handleRemovePlayer}  
            highScore ={player.isHigh}         
          />
        )}
        <AddPlayerForm addPlayer ={this.handleAddPlayer}/>
      </div>
    );
  }
}

export default App;