NGXS: Update deep level nested array state

Viewed 244

So I have the following state:

[
   {
      name: "Main Tree",
      branches: [
        {
          name: "Branch 1",
          branches: []
        },
        {
          name: "Branch 2",
          branches: [
            {
              name: "Sub Branch 1",
              branches: []
            }
          ]
        }
      ]
   }
]

My question is, how do I append another branch under the branches in Sub Branch 1 using state operators? I tried the solution on this link (State Operators) but it converts the data from array into object which is not the desired output.

Also the above scenario is just an example, my use-case is that it could be an infinite level of sub branches with branches inside them.

Thank you in advance.

1 Answers

This should work for the above example:

// import { append, patch, updateItem } from '@ngxs/store/operators';

interface BranchTree {
  name: string;
  branches: BranchTree[];
}

type BranchStateModel = Array<BranchTree>;

//..
@Action(UpdateSubBranch)
updateSubBranch({ setState }: StateContext<BranchStateModel>) {
  const newBranch: BranchTree = {
    name: 'Sub 1 of Sub Branch 1',
    branches: [],
  };
  setState(
    updateItem(
      (branch) => branch.name === 'Main Tree',
      patch({
        branches: updateItem<BranchTree>(
          (subBranch) => subBranch.name === 'Branch 2',
          patch({
            branches: updateItem<BranchTree>(
              (subBranch) => subBranch.name === 'Sub Branch 1',
              patch({ branches: append([newBranch]) })
            ),
          })
        ),
      })
    )
  );
}

However, you need to implement your recursive solution for the infinite tree based on the above solution.

Read more about NGXS State Operators here: https://www.ngxs.io/v/v3.7/advanced/operators

Related