Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript React Basics Understanding State Remove Items From State

Gremyko Coleman
Gremyko Coleman
8,774 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,774 Points

Thanks Robin and Kod, now it makes sense