0

The initial state looks like this:

const INITIAL_STATE = {
    myArray: []
};

Now in my reducer, I want to append a new object to the existing array. I came up with something like this but it doesn't work as expected.

    case ADD_TO_ARRAY:
        return {
            ...state,
            myArray: [...state[ { action.payload.key: action.payload.value} ]]
        };

Note: I want to create a new object, in line, using the key and value passed in the action payload.

1 Answer 1

5

with ES6 you can have dynamically calculated object keys
just add a variable to be evaluated in square brackets []

case ADD_TO_ARRAY:
  return {
    ...state,
    myArray: [...state.myArray, [ { [action.payload.key]: action.payload.value} ]]
};
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.