angulartypescriptngrxngrx-reducers

how to update state with arrays in ngrx


I am trying to migrate my application to use ngrx. One of the first features is loading my actual content and displaying it, but I have some issues.

I defined this in my reducer:

export const collectionFeatureKey = 'colecciones';

export interface CollectionsState {
  lista_creadas: Array<Collection>;
  lista_asignadas: Array<Collection>;
  lista_grupos: Array<Collection>;
}

export const initialState: CollectionsState = {
  lista_creadas: [],
  lista_asignadas : [],
  lista_grupos: []
};

I prepared and effect that get the information from API. IT work fine. But I don't know how to asign the value of the three arrays to the state, Actually i'm doing this:

const collectionsReducer = createReducer(
    initialState,
    on(CollectionActions.loadCollections, state => state),
    on(CollectionActions.loadCollectionsSucess,
      (state, { colecciones }) => {
        return {
          ...state,
          colecciones
        };
      }
    ),
    on(CollectionActions.loadCollectionsError, state => state),
/*...*/

But it doesn't work as expected.

enter image description here

What I am doing wrong? Thanks in advance


Solution

  • colecciones is an object, and you will have to assign each array to the state's array:

       on(CollectionActions.loadCollectionsSucess,
          (state, { colecciones }) => {
            return {
              ...state,
              lista_creadas: colecciones.lista_creadas
              lista_asignadas: colecciones.lista_asignadas
              lista_grupos: colecciones.lista_grupos
            };
          }
        ),
    

    There's a shortcut for this with the spread operator:

       on(CollectionActions.loadCollectionsSucess,
          (state, { colecciones }) => {
            return {
              ...state,
              ...colecciones
            };
          }
        ),
    

    But since your action contains the payload which is equivalent to the next state you can also do:

      on(CollectionActions.loadCollectionsSucess,
          (state, { colecciones }) => {
            return colecciones
          }
        ),