Chrillewoodz Chrillewoodz - 17 days ago 10
TypeScript Question

Angular 2 with ngrx/store, updating property of state object without overwriting the entire object

I'm trying to assign a new property of a state object but I can't seem to set it without setting a whole new object, I only want to add a property, not create a whole new object with just that one property.

Here's my reducer:

const initialState = {
all: [],
single: {}
}

export const ModelsReducer: ActionReducer<any> = (state: IModelsStorage = initialState, action: Action) => {

switch(action.type) {

case GET_MODELS_SUCCESS: return Object.assign({}, state, {
all: [...action.payload.data]
});

case GET_MODEL_SUCCESS: return Object.assign({}, state, {
single: action.payload.data
});

// How do I only update the single object without overwriting the whole thing?
case GET_VARIANTS_SUCCESS: return Object.assign({}, state, {
single: {
variants: action.payload.data
}
});

default: return state;
}
}


How can I do this?

Answer

With another one Object.assign...

case GET_VARIANTS_SUCCESS: return Object.assign({}, state, {
  single: Object.assign(state.single, {
    variants: action.payload.data
  })
});