loliki
loliki

Reputation: 957

Redux change a reducer of type object

So I have the following reducer

const objectType = (state = {type: 0, image:defaultImage, moreOptions: {tap: 0, griff: 0} },
    action) => {....

case 'CHANG_OPTIONS':
      return state = {...state, moreOptions: {tap:action.tap, griff: action.griff}}

This is the action, so I get a dynamic category and assign the id of the product.

export const changeOptions = (category, id) => {
    return {
        type: 'CHANG_OPTIONS',
        [category]: id,
    }
}

An example of dispatch would be

dispatch(changeOptions('tap', 0))

Now whenever I click on a tap or a griff, my object remove the other category from the list.

Here is a screenshot from the Redux Debugger tool

enter image description here

I'm sure that the problem is in my reducer: moreOptions: {tap:action.tap, griff: action.griff} Is there a way I can spread the object and update only the one that was changed?

Upvotes: 0

Views: 28

Answers (1)

michael
michael

Reputation: 4173

It's because you're overwritting both tap and griff value regardless of their input value. Try below.

const newOptions = {};
if (action.tap) {
  newOptions.tap = action.tap;
}
if (action.griff) {
  newOptions.griff = action.griff;
}
return (state = {
  ...state,
  moreOptions: {
    ...state.moreOptions,
    ...newOptions
  }
});

Upvotes: 1

Related Questions