Bomber
Bomber

Reputation: 10957

Add property to object in reducer

I am trying to add a property to my state currentDrink:

{
    currentDrink: {
      ...action.payload
    },
    ...state
}

I would like my state to be:

currentDrink: {
    prop: 1,
    prop: 2,
    ...etc
},

My state only every contains one property.

Upvotes: 0

Views: 2197

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281696

The problem is very trivial, the order in which the spread operator syntax is used decides the final result

So

{
    currentDrink: {
      ...action.payload
    },
    ...state
  }

is different from

 {
    ...state,
    currentDrink: {
      ...action.payload
    }
  }

In the first case, if state already contains, currentDrink property it will your custom change to currentDrink will be overwritten with the states one.

In the second second, case the custom currentDrink object will override what is present in state, if at all. However

currentDrink: {
    ...action.payload
}

will destructure action.payload and assign it to currentDrink and override whatever was present in the currentDrink object in state.

You should probably use

{
    ...state,
    currentDrink: {
      ...state.currentDrink,
      ...action.payload
    }
}

Upvotes: 1

Related Questions