Search code examples
angularngrxngrx-store

error Cannot delete property '2' of [object Array] using splice static method on my reducer NgRx


I´m getting this error on console:

TypeError: Cannot delete property '2' of [object Array] at Array.splice

when I try to use static method splice over the array I passed on my reducer to update the store

Here how the store's property sideNavCustomGrids looks like on NgRx Store DevTools before I fire the removeSideNavCustomGrid action. It´s an array of objects

enter image description here

and here the structure of the action removeSideNavCustomGrid inside my reducer:

export const customDistributionsReducer = createReducer(
  initialState,

  on(CustomDistributionsActions.updateSideNavCustomGrid, (currentState, action: any): any => ({
    ...currentState,
    sideNavCustomGrids: [...action.list],
  })),

  on(CustomDistributionsActions.removeSideNavCustomGrid, (currentState, action: any): any => {
    const idIndex = action.list.findIndex((e:any) => e.id === action.id);
    action.list.splice(idIndex, 1);
    return {
        ...currentState,
        sideNavCustomGrids: [...action.list],
    }
  })
);

My investigations lead me to think that the error is related to the immutability of the NgRx store. I think your values are read only


Solution

  • both actions and store are usually readonly in development mode. it can be configured in StoreModule.forRoot(...) config.

    to use splice you could create local array copy in your reducer and modify it as you want.

    const list = [...action.list];
    list.splice(idIndex, 1);
    return {
        ...currentState,
        sideNavCustomGrids: list,
    }