tempomax
tempomax

Reputation: 793

Changing a nested object in Redux using spread operators when the keys are dynamic?

I am trying to store a nested object in redux, but I am using dynamic keys. Here is an example of what it would look like:

// In my Redux Reducer
const initialState = {
    stuff: {
        <dynamic_key>: { name: 'bob', title: 'mr' },
        <dynamic_key>: { name: 'eve', title: 'ms' },
        <dynamic_key>: { name: 'car', title: 'na' },
    },
};

So I have a redux state called stuff that should hold my nested objects.

However, I cannot correctly save my data. I know react states all have to be immutable, so I am using the spread operator and Object.assign() to create a new object:

const reducer = ( state = initialState, action) => {
// ....
        case UPDATE:
            return { ...state, 
                stuff: { 
                    Object.assign({}, action.key, {
                        name: action.name,
                        title: action.title
                    })
                }
            };
// ....
}

The above is trying to create/update the entire <dynamic_key>, using action.key as the dynamic_key, action.name as the name, and action.title as the title.

An extra tidbit is that if action.key (the dynamic key) doesn't already exist in the redux store stuff, then it should be created rather than error out.

What am I doing wrong? I think I am not using Object.assign() correctly, or not using the spread operator correctly?

EDIT:

Here is my redux action:

export const update = s => ({ type: "UPDATE", payload: {key: s.key, name: s.name, title: s.title} });

Upvotes: 1

Views: 728

Answers (1)

Devin Fields
Devin Fields

Reputation: 2544

Using object spread operator

It seems like in you're case, you've got a couple additionally unnecessary steps. If stuff is supposed to be an object that contains your dynamic keys/value pairs, then you should have:

stuff: Object.assign({}, state.stuff, {[action.key]: {etc...}})

OR

stuff: {
  ...state.stuff
  [action.key]: {name: etc...}
}

Keep in mind that every argument to Object.assign, must be an object. It seems like you are supplying the second argument a string. I also assume you already have a compiler that allows you to safely use the object spread syntax.

EDIT: added state.stuff to both examples so as not to override previous properties.

Upvotes: 3

Related Questions