1

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 })
  };
};
0

2 Answers 2

3

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
    }
};
Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

Thank you for the resource.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.