Home:ALL Converter>Changing a nested object in Redux using spread operators when the keys are dynamic?

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

Ask Time:2018-06-07T02:34:00         Author:tempomax

Json Formatter

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

Author:tempomax,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/50727307/changing-a-nested-object-in-redux-using-spread-operators-when-the-keys-are-dynam
yy