Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to declare two actions in ? : format?

My code is as below:

if(existingWishlistItem) {
  return wishlistItems.map(wishlistItem => 
    wishlistItem.id === wishlistItemToAdd.id
    ? toast.error('This item is already in your wishlist')
    : wishlistItem
  )
}

I want this function to check if there are existing wishlist item in the array, then it pop up an error message to user and return back the wishlistItem array. But I find that I just can write one action after the ‘?’, so are there any ways to pop up the message and return back the wishlistItem at the same time?

Thanks for help!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It’s possible to do this with the conditional operator, but it’s not a good idea. It’s hard to read, hard to debug, and easy to get wrong.

Instead, just use an if:

if (existingWishlistItem) {
    for (const {id} of wishlistItems) {
        if (id === wishlistItemToAdd.id) {
            toast.error('This item is already in your wishlist');
            break; // I assume the ID values are unique, so you can stop here
            // Or: `return wishlistItems;` if you don't need to make a
            // copy in this case
        }
    }
    return wishlistItems; // If you don't need to make a copy
    // Or: `return wishlistItems.slice()` if you do need to make a copy
}

(Or — again assuming id values are unique — you could use find instead of the for-of loop to find the existing item.)


For completeness, you can use the comma operator to do two things in any expression (including the operands of the conditional operator): (first, second). The comma operator evaluates its left-hand operand, throws away that result, and then evalutes its right-hand operand and takes that value as its result. Applying that to your example:

// DON'T DO THIS
if (existingWishlistItem) {
    return wishlistItems.map(wishlistItem => 
        wishlistItem.id === wishlistItemToAdd.id
            ? (toast.error('This item is already in your wishlist'), wishlistItem)
            : wishlistItem
    );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading