javascriptreactjsreduxreducespread-syntax

adding objects to collections elements using spread syntax


I'm working with react redux and want use spread syntax on a reducer in order to return and updated object which contains a collection element where I want to add objects.

I have the following reducer logic which is not working because the collection is being filled with the payload object values instead of the object itself:

export default function(state = INITIAL_STATE, action){
switch (action.type){
    case CREATE:
        return {...INITIAL_STATE,collection:{...state.collection,...action.payload}};
    default:
        return state;
}

}

The payload is an object like:

{
'DG67QBXQJW7':{
    key:'12345',
    price:'15',
    name:'test'
}

};

And the returned state I would like to have something like:

{
name:'items',
collection:{
    'DG67QBXQJW7':{
        key:'12345',
        price:'15',
        name:'test'
    },
    'FB843VUV3N9':{
        key:'67890',
        price:'11',
        name:'test2'
    }
}

}

But I got with my previous showed logic something like:

{
name:'items',
key:'12345',
price:'15',
name:'test'

}

If someone could help or show me an advanced and good spread syntax guide for this kind of operations would be great.

Thanks in advance.


Solution

  • You just need to use your current state, not INITIAL_STATE, as the base of your object.

    return {...state, collection: {...state.collection, ...action.payload}};
    

    Test example:

    const state = { name: 1, collection: { test3: { a: 3}, test4: {a: 4}}};
    const payload = { test5: { a: 5 }};
    
    console.log({...state, collection: {...state.collection, ...payload}});