Sean
Sean

Reputation: 545

Updating property of nested object in Redux using action

Inside my reducer, my initial state has a structure like the following:

const initialState = {
    showOverlay: false,
    chosenAnimal: null,
    sliderValue: 0,
    colorValues: {
        a: null,
        c: null,
        g: null,
        t: null,
        bg: null
    }
};

I'm attempting to update one of the colorValues properties based on an action.type.

return {
    ...state,
    colorValues: {...state.colorValues, action.basePair: action.colorHex}
};

action.basePair is giving me a parsing error which makes it seem as if I cannot set the property name dynamically using action. If I change action.basePair to gfor example, then the expected behavior occurs and the value of the property g is indeed updated as expected.

But is there anyway to do this so that I can set the property name dynamically through action? Thank you.

edit: The code of my action is the following:

const mapDispatchToProps = dispatch => {
  return {
    onSetColorValue: (basePair, colorHex) =>
      dispatch({ type: "SET_COLOR_VALUES", basePair: basePair, colorHex: colorHex })
  };
};

Upvotes: 1

Views: 555

Answers (2)

Anuradha Kumari
Anuradha Kumari

Reputation: 703

when using dynamic value as key, we can use the square brackets notation. Please see below:

return {
    ...state,
    colorValues: {
          ...state.colorValues, 
          [action.basePair]: action.colorHex
    }
};

You can visit below link for more details: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors

Upvotes: 2

Oleksandr T.
Oleksandr T.

Reputation: 77522

action.basePair is giving me a parsing error which makes it seem as if I cannot set the property name dynamically using action.

Wrap action.basePair to [action.basePair]

return {
    ...state,
    colorValues: {...state.colorValues, [action.basePair]: action.colorHex}
};

Also, it is a good practice to use payload key for action params

dispatch({ type: "SET_COLOR_VALUES", payload: { basePair, colorHex })

Reducer

return {
    ...state,
    colorValues: {
      ...state.colorValues, [action.payload.basePair]: action.payload.colorHex
    }
};

Upvotes: 3

Related Questions