Removing an item and its children in ngrx

2k Views Asked by At

I am new to ngrx store and confused with the placement of logic i.e whether looping through array should go to reducer or component. I have an array of objects of type Item and have to delete an item. While deleting an item, I have to delete its reference in parent's children as well as all its children.

    export class Item {
      id: string;
      message: string;
      children: string[];
    }
    

The children property of Item contains ids of objects of type Item itself.

    Items: Item[] = [
     {id: "1", "message": "First Message" , children:["4","5"]},
     {id: "2", "message": "Seccond message" , children:["3"]},
     {id: "3", "message": "First child Message" , children:[]},
     {id: "4", "message": "Second child message" , children:["6"]},
     {id: "5", "message": "third child message" , children:[]},
     {id: "6", "message": "child message" , children:[]},
    ]
    

I have to remove an item and it's corresponding children from the array on dispatch of action "DeleteItemByID" e.g. if I am deleting an item with id=4, it updates the item with id="1" and remove the "4" from its children's array. The delete action then deletes the children of the item which is the item with id="6" and then finally deletes the item with id="4".

    Items: Item[] = [
     {id: "1", "message": "First Message" , children:["5"]},
     {id: "2", "message": "Second message" , children:["3"]},
     {id: "3", "message": "First child Message" , children:[]},
     {id: "5", "message": "third child message" , children:[]},
    ]
    
    export class DeleteItemByID implements Action {
        readonly type = "DeleteById";
     /**
      * Constructor
      * @param payload The id of the discussion to remove
      */
        constructor(public payload: string) { }
    }
    
    /*App state*/
    export class AppState{
        items: Item[]
    }
    
    /* reducer */
    export function reducer(state: AppState = [], action  ) : AppState{
       switch (action.type) {
            case "DeleteById":
                /* Delete Logic*/
                return {};
            default:
                return state;
    }

Help me out the best approach I should be taking for delete operation.

1

There are 1 best solutions below

0
Aakash Garg On

They correct answer will differ case to case,

Case 1:- If you want to reuse this deletion behavior at multiple places, i.e. at multiple components/services. Create two different actions i.e. DeleteChildrenItemById and DeleteItemById.

OR

You can create a service method which will delete required items from array and dispatch a whole new array to reducer to replace existing one, that will help you avoid complex login in reducer.

Case 2 :- If this behavior is only required for this component then do the deletion in component and dispatch this new array to reducer.