Home > Enterprise >  Need explanations for 'React toggle "Show All" and "Show Winners" doesn
Need explanations for 'React toggle "Show All" and "Show Winners" doesn

Time:10-07

I have hard time understand this block of code in this post.

I understand after button's clicked, the toggleWinner function's triggered. I don't understand how come 'prev' becomes '!prev' so the if statement's executed?

Could someone please explain this piece of code to me? Thank you.

The Post: React toggle "Show All" and "Show Winners" doesn't work

The full solution code here

const toggleWinner = () => {
    //winner = false
    filterWinner(prev => {
        if(!prev) { // winner = true
            const winners = movies.filter((movie) => movie.winner === "True");
            setMovies(winners);
        }
        else {
            setMovies(movies);
        }
        return !prev
    });
};

CodePudding user response:

filterWinner should perhaps be named setWinner or setWinnerFilter.

If a function is passed when setting a React state like that, whatever is returned at the end of the function is the new winner state. Since we return !prev, we invert whatever boolean value that winner. Hence, it toggles winner between true and false.

CodePudding user response:

The if (!prev) checks to see if prev is falsey. It basically says "if prev doesn't exist or if prev is false".

The return !prev part will return the opposite of the current prev value. So if prev is true and you call return !prev it will return false since it is the "opposite" of true.

This demo should clear it up:

console.log(`!true should be false. '${!true}'`);
console.log(`!false should be true. '${!false}'`);

  • Related