JavaScript React Basics Understanding State Remove Items From State

Gremyko Coleman
Gremyko Coleman
8,675 Points

handleRemovePlayer function

I am confused on when to use a return and when not to in writing a function for a state in this example when we created the handleRemovePlayer function, why did we use a return{}? But in the previous functions for increment score and decrement score we didn't use a return{} in the function?

ex)

no return used and also 2 parentheses ,this.setState( prevState =>( { } ) );

addScore = ()=>{
      this.setState( prevState =>({
          score:prevState.score + 1
      }));
  }

with the return

handleRemovePlayer = (id) =>{
        this.setState( prevState => {
            return{
                players: prevState.players.filter()
            }
        });
    }
Robin Siegl
Robin Siegl
11,157 Points

I think it's because in the first code block you just set the score (don't ned to get anything back) and on the second code block you probably need to get the value back. Maybe i'm wrong here, but i hope someone can give a clear answer to this.

2 Answers

In arrow functions you can have an explicit or implicit return, but it's always returning something (even undefined). The second code you gave can be rewritten like this:

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

The extra pair of parentheses around { players: prevState.players.filter() } are needed so the interpreter doesn't read them as the initial braces of a code block, rather than an object literal, which is what we want.

Robin is right. You use return when you want something back. In the first example, we're just updating the prev state by adding 1 on click. In the second, we are filtering to remove the deleted player and return the rest of the players that were not deleted.

Gremyko Coleman
Gremyko Coleman
8,675 Points

Thanks Robin and Kod, now it makes sense