Friday 2 December 2016

javascript - What does ...state do exactly?




I'm trying out NgRx (redux) in Angular and the ...state in the example below, I can not fully understand. I searched for it and generally understood it as spread, but not sure why the data attributes in the Interface State are repeated in the return{} block of the reducer's switch, as the ... would spread them anyway? Can anyone help me understand this please?



export interface State {

sessionData: Map;
requesting: boolean;
hasError: boolean;
status: StatusModel;
}

export function sessionReducer(state: State = INITIAL_STATE, action: Session.Actions): State {
switch (action.type) {
case Session.REQUEST_SESSION_DATA:
return {

...state,
requesting: true,
hasError: false,
status: undefined,
};
}
}


PS: I've looked at the thread here and generally get that spread does exactly that, spread out. But here in the context of Redux/NgRx, trying to understand why the return{} has ...state and the three additional properties.



Answer



The point of the state is that it's inmutable (a new object is returned, instead a modified one). So, if you want to modify the state adding new values to it you need to return the current state plus the new values yo want to add to the previous state. In that example with the spread operator ..., you are returning a new inmutable object containing the previous state plus three new properties requesting, hasError and status. You can think of doing this:



export function sessionReducer(state: State = INITIAL_STATE, action: Session.Actions): State {
switch (action.type) {
case Session.REQUEST_SESSION_DATA:
state.requesting = true;
state.hasError: false;
state.status: undefined;


return state;
}
}


But you cannot do this, because you are breaking the philosophy of the state, new inmutable objects instead of modified ones :)



In your example, we need to know how the INITIAL_STATE is initialized, but I think that it only contains the sessionData property. So, in that example you are returning the sessionData plus the remaining properties.



In the link below you can see that the spread operator is a common used operator in the Redux world to return the current state as a new object (it's a Redux for React example, but it works exactly the same in Angular).




In Angular it's a very common pattern using the Redux pattern with the OnPush change detection strategy, because you are telling Angular to check only for reference changes in the component @Input instead of compare objects comparing property by property. That's a big advantage in performance.



Use of Spread Operator with Redux


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...