james emanon
james emanon

Reputation: 11807

Reactjs: Obj is being reassigned when using in setState, something odd

So, I have this base object:

const obj = {
    name: 'bill',
    age: 44,
    cid: 0
}

and in various parts of my application, I "reset" to this obj on my state. Problem is, IF I try to reassign the obj, cid is always overwritten - if I explicitly reassign, it's clean.. ala.

// this is psuedo code, but this would break in that
// var2 now has some bleedover with other objects dirtying things up
this.setState({
    key1: [_.merge([whatetever], {this.state.var1}],
    key2: [this.obj]
})

note: when I log out 'this.obj', it was mutated someway.

// this way is fine

this.setState({
    key1: [_.merge([whatetever], {cid},{this.state.var1}],
    key2: [{
        name: 'bill',
        age: 444,
        cid: 0
    }]
})

but explicitly reassigning a whole object on 5 or so places is lame.. why can't i just reassign the obj reference. I've never run into this before in all my years... of course, it is a reassignment issue and perhaps something with es6 reverse assignment?

anyways your thoughts?

Upvotes: 0

Views: 31

Answers (1)

Mike
Mike

Reputation: 1452

Try the following:

key2: Object.assign({}, state['key2'], this.obj)

Although it is strange to be using this.obj. Shouldn't that be either props or state?

I'm still not quite sure what you are trying to do by "resetting".

Upvotes: 1

Related Questions