1

How to change value all of keys "isVisible"?

state = {
    players: [
      {
        id: 0,
        name: 'Gabriel',
        isVisible: false,
      },
      {
        id: 1,
        name: 'John',
        isVisible: false,
      },
    ]

I have tried:

handleclick = () => {
    let players = this.state.players
    players = players.map(player => player.set("isVisible", true))
    this.setState({
      players
    })
  }

It throw error because president.set is not a function. Any ideas?

ManuLisek
  • 87
  • 1
  • 1
  • 6

1 Answers1

2

try this:

  handleclick = () => {
        let players = this.state.players
        players = players.map(player => {player.isVisible = true; return player;}))
        this.setState({
          players
        })
      }
Shay Moshe
  • 482
  • 4
  • 16
  • 1
    This solution mutates state. You could simplify and also avoid mutation like this: `players.map(player => ({...player, isVisible: true}))` – Brian Thompson Nov 02 '20 at 21:10
  • @BrianThompson does it really mutate state even though he declares a new let players? – MWO Nov 02 '20 at 21:15
  • @charly1212 yes. JavaScript objects and arrays are stored as references, so the assignment `let players = this.state.players` is actually assigning a reference to the state array, not just its value. You can test it out to see that mutations occur in both arrays, or check out [this answer](https://stackoverflow.com/a/59738588/9381601) I wrote about it (with runnable examples, see "explanation" heading). – Brian Thompson Nov 02 '20 at 21:23