Properly returning nested state with Object.assign

Viewed 573

I'm working on a React/Redux application and for the most part, everything has been working smoothly.

Essentially, it's a todo application that has categorization built in.

I'm having trouble properly returning the full existing state in my reducer when the user adds a todo-item inside a category.

The redux state before I dispatch the ADD_ITEM action looks like this:

{
items: {
    "HOME": [["Do laundry", "High Priority"],["Feed kids", "Low priority"] ],
    "WORK": [["Get promotion", "High priority"],["Finish project", "Medium priority"] ],
    "BOTH": [["Eat better", "Medium priority"],["Go for a run", "High priority"] ],

},
settings: {
    Test: "test"
}
}

The user navigates to a category(pre-made, haven't implemented creating them yet) and can create a new todo-item with a name and a priority. This dispatches an action that returns an array like [category, name, priority].

Currently in my reducer, I have it where it is successfully adding the item, but it is emptying/overwriting all the existing categories.

My reducer looks like this:

case types.ADD_ITEM:
let cat = action.payload[0];
let name = action.payload[1];
let priority = action.payload[2];
return Object.assign({}, state, { items: { [cat]:   [...state.items[cat], [name, priority]]}});

I've tried creating a new object first with all the combined items like so:

let combinedItems = Object.assign({}, state.items, { [cat]: [...state.items[cat], action.payload] });

If I console.log the above combinedItems, I get the exact object that I want items to be. However, I'm struggling to have the final object returned by the reducer to reflect that.

When I tried something like below, I got an object that contained combinedItems as a separate key inside items.

        return Object.assign({}, state, { items: { combinedItems, [cat]: [...state.items[cat], [name, priority]]}});

Can anyone help me get my final redux state to contain all the existing categories/items + the user added one? I would really appreciate the help.

1 Answers
Related