Doing It Wrongly
let newState = Object.assign(state); newState.counter = 13; newState.rooms.name = 'hey now';
Help From Strangers
let newState = Object.assign({}, state);
let newState = Object.assign({}, state, { counter: 13 });
Writings about one coder's stories & experiences.
I just went through a pretty embarasseing episode of fighting with a large codebase to figure out a bug, and it turned out in the end that the issues were being caused by improper use of the Object.assign method. In particular, I was using it to manage the state inside my reducer function in an ngrx store, and it was screwing with my whole app! I hope I can remember that you need to first pass in an empty object to Object.assign, and then you pass the object that you want to "assign onto" that empty object.
Doing It Wrongly
Suppose that this code lives in your reducer function, and it is run when an action of some specific type comes in:
let newState = Object.assign(state); newState.counter = 13; newState.rooms.name = 'hey now';
This code above is dreafully bad news. When declaring the newState variable what I meant to do was make a clone of state, assign it to the newState variable, and then modify the newState. However, what's actually happening here is that Object.assign is not making a clone but returning a reference to state so the next lines are actually mutating the state itself! That's no good!
Help From Strangers
I was so baffled by the weird things that were happening in my view (only some bindings were updating when I would dispatch actinos to the store) that I posted this question on stack overflow: Thankfully, yurzui posted a great answer explaining how I was calling Object.assign wrongly and how that was causing the strange behavior. The correct way to call Object.assign is with an empty object in the beginning like this:
let newState = Object.assign({}, state);
and he also pointed out that you can put your modifications to the new state right in the Object.assign call like this:
let newState = Object.assign({}, state, { counter: 13 });
Thanks yurzui!
0 Comments
Your comment will be posted after it is approved.
Leave a Reply. |
AuthorThe posts on this site are written and maintained by Jim Lynch. About Jim...
Categories
All
Archives
March 2023
|