Array.map returns null in a redux reducer using arrow functions

Viewed 100

Consider this array of items:

items:[
 {
  _id: '111',
  quantity: 3
 },
 {
  _id: '222',
  quantity: 7
 }
]

I need to increment the value by 1 by looping using Array#map with CURLY BRACES following the arrow => (look at the code below), but this make the myNewItems null, and I guess this is because the variable item gets lost along the way and ends up with myNewItems to be null

This is how I have iterated in a redux reducer

return {
  ...state,
  myNewItems: items.map((item) => {
    var itemId = '111'

    item._id == itemId ?
      {
        ...item,
        quantity: item.quantity + 1
      } :
      item
  })
}

Now this makes myNewItems to be null instead of it having updated array of items like this below

items:[
 {
  _id: '111',
  quantity: 4 //has been incremented by 1
 },
 {
  _id: '222',
  quantity: 7
 }
]

How do I get through this?

2 Answers

You are missing the return statement in your map callback.

items.map(
           (item) =>{
              var itemId = '111'
              return item._id == itemId?
              {...item, quantity: item.quantity + 1
              }:item
        })

missing return in map higher order function try this

return item._id == itemId
    ?{...item, quantity: item.quantity + 1}
    :item
Related