Skip to content
Advertisement

reactjs context reducer increment data

How to increment the array value inside the object.

I tried the code below but It’s removing the garments array and replacing it with shirts: Nan value

export const initialState = {
    booking: {
       expPrice: 0,
       garments: [
        {
            shirts: 0
        },
        {
            pants: 0
        },
        {
            etc: 0
        }
    ]
},
bookings: []
};

export const bookingsReducer = (state, action) => {
   switch (action.type) {
    case 'INCREMENT_SHIRT': {
        return {
            ...state,
            booking: {
                ...state.garments,
                shirts: state.shirts + 1 // how to increment 
            }
        };
    }
    default:
        return state
   }
}

Advertisement

Answer

You’re trying to spread the properties of your garments array into your new booking object, however, as state doesn’t have a garments property you’ll be spreading undefined (which is a no-op). Moreover, if it did hold your array, you would be spreading the indexes of your array as keys to your new object. You’re also adding a shirt property to your booking object, which you don’t want to do as you want to keep this property inside the objects of your garments array.

Instead, spread the state.booking properties into your booking object, and then overwrite the garments property with a new array to be the mapped version of your current garments array. When you’re mapping, if you find an object with a shirts property, you can increment its value by adding one to the current value, otherwise, you can return the current object:

return {
  ...state,
  booking: {
    ...state.booking,
    garments: state.booking.garments.map(
      obj => obj.hasOwnProperty('shirts') ? {shirts: obj.shirts+1} : obj
    ) 
  }
};
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement