Steve
Steve

Reputation: 4985

Cloning an object within a redux reducer

I've recently learned React and Redux, and right when I thought I was getting the hang of it I've been hung up on this.

In my reducer I'm under the impression that the spread operator should create a new instance of the object at a difference memory location. However, using === to compare the objects returns true which I believe means the objects are the same instances.

const initState = {

    loadcases: {
        1: {
            isActive: false,
            profile: 'UB'
        },
        2: {
            isActive: true,
            profile: 'PFC'
        }
    }
}


const designInput = (state=initState, action={}) => {

    let newState = {...state}; //clone design input state
    console.log(newState.loadcases === state.loadcases)
    // Prints: TRUE ---- WHYYYYYYY????????????

    // goes on to modify newState before returning it. 
}

The redux logger is showing my previous state to already equal the new state which has me thinking that this here is interfering with the store directly. I've read through some redux docs and other posts which make me believe I have set everything else up correctly.

Any resources to educate me more on this issue is also much appreciated.

UPDATE:

Jayce's answer was exactly what was happening.

This SO post outlines which method for a deep clone will be suitable. For me, it's likely I'll want to store dates and other data so I've chosen to use lodash cloneDeep method.

So now: console.log(cloneDeep(state) === state.loadcases); // false

Upvotes: 2

Views: 1503

Answers (1)

Jayce444
Jayce444

Reputation: 9063

Your assumption that the spread operator creates a new object is true, however it doesn't do a deep clone of objects. It copies the references of nested values over to the new object, so that's why it's printing that they're equal.

If you want to deeply clone something with nested values you can't use spread, you have to use another method. You could use a library like lodash, or something such as JSON.parse(JSON.stringify(obj)), there's multiple options just google for something like "Javascript deep clone object"

Upvotes: 2

Related Questions