I am trying to publish an updated object but not trying to change the state through the following code in react:
addPlaceToSearch = (place) => {
if (place != this.state.search_text) {
var search = $.extend({}, this.state.search);
if (!search.added_places.includes(place)) {
search.added_places.push(place);
PubSub.publish('searchUpdated', search);
}
}
}
Thus, I am using $.extend({}, this.state.search)
to clone the object into another variable, modify that particular variable and then publish it. But when I execute the line 5
, and I put a breakpoint on line 6
, I can see that the this.state.search
is also changed with place
being pushed in it's added_places
key (which I do not want). How is this happening? And how can I prevent it? I have also tried Object.assign({}, this.state.search)
instead of $.extend({}, this.state.search)
.
EDIT
I even tried the most trivial solution, here it is:
addPlaceToSearch = (place) => {
if (place != this.state.search_text) {
if (!this.state.search.added_places.includes(place)) {
var xyz = {};
for (var key in this.state.search) {
xyz[key] = this.state.search[key];
}
xyz.added_places.push(place);
PubSub.publish('searchUpdated', xyz);
}
}
}
Still, the xyz.added_places.push(place)
line changes my this.state.search object too! Kindly help me out.