Deleting items recursively from ngrx store

I am currently using Angular 10 along with the ngrx store library, but I am facing difficulty in understanding how to recursively delete items from the ngrx store. Within the store, there is a nested array of objects, and I need help with deleting an object based on its id. I attempted to use splice and a function, but encountered this error:

Cannot assign to read only property '0' of object '[object Array]'

I'm not sure what I am doing wrong, could someone please assist me?

Here's an example of the data structure:

[
  {
    "id": 414,
    "name": "mail.ru",
    "is_main": true,
    "subdomains": [
      {
        "id": 423,
        "name": "en.mail.ru",
        "is_main": false,
        "subdomains": [
          {
            "id": 429,
            "name": "gw.mail1.ru",
            "is_main": false,
            "subdomains": [
              {
                "id": 426,
                "name": "gw.mail3.ru",
                "is_main": false,
                "subdomains": []
              }
            ]
          }
        ]
      },
      {
        "id": 425,
        "name": "gw.mail.ru",
        "is_main": false,
        "subdomains": []
      }
    ]
  }
]

This is my current store reducer:

 case UserInfoActionTypes.UPDATE_DOMAINS_LIST: {
            return {
                ...state,
                domainsInfo: deleteItems(state.domainsInfo, [parseInt(action.payload.id, 10)]),
                errorMessage: null
            };
        }`

Below is the recursive function I have created for deletion:

export function deleteItems(array, ids) {
    let i = array.length;
    while (i--) {
        if (ids.indexOf(array[i].id) !== -1) {
            array.splice(i, 1);
            continue;
        }
        array[i].subdomains && deleteItems(array[i].subdomains, ids);
    }
    return array;
}

Answer №1

In order to achieve the desired outcome, it is essential to generate fresh entities for each element in the state. The function deleteItems() can be structured as follows:

export function deleteItems(array, ids) {
    let result = [];
    for(item of array) {
        if (!ids.includes(item.id)) {
            result.push({
              ...item,
              subcategories: deleteItems(item.subcategories, ids),
            })
        }
    }
    return result;
}

I may have overlooked a specific aspect since my exposure to ngrx is limited.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to incorporate multiple conditions within a React component?

When working in React, I have the ability to conditionally render any div using the following code snippet: {hasContent && <span>{value}</span> } Recently, I attempted to include two conditions as follows: {hasContent || hasDesc &am ...

Repeatedly Triggered JQuery AJAX Calls

On my web page, I have implemented a feature that allows users to search for an address using a GIS server's web-service. This functionality is triggered by a button click event which calls a JQuery AJAX method. Upon successful retrieval of address da ...

Is there a method in Node.js to pause file reading and terminate the entire process within the eachLine function of line-reader?

Here is a code snippet that I've been working on: const lineReader = require('line-reader'); var truevar = false; async function readLines(filename, processLine) { return new Promise((resolve, reject) => { lineReader.eachLin ...

Steps to obtain the download URL from AngularFireStorage after uploading the file using the getDownloadUrl() method

After successfully uploading images into my firebase storage, I want to retrieve the downloadURL and add it to my firestore database. When console logging "url", I am able to see the desired link. However, I am facing difficulties in using it. When attemp ...

Creating JavaScript functions that accept three inputs and perform an operation on them

Apologies in advance if there are any silly mistakes as I am new to Javascript. I want to add "salary", "pension", and "other" together, then display the result in an input field when a button is clicked. Not sure if I have used the correct tags in my cod ...

Template is not populating with data (Angular)

Currently, I am honing my Angular skills by working on a simple project. I have been seeking answers to my queries on Stack Overflow as they closely align with the issue I am facing. My challenge lies in displaying asynchronous data before it is initialize ...

Filtering nested objects in ReactJS can be achieved by utilizing methods like map

Data sample: nodes:[ { label:"Egor1", value:"Egor1", restorePoint:"25/10/2017 10:00:29 PM", vmcount:"2", restorePointsCount:"", children:[ {label:"disk111111111111111", value:"disk1", restorePoint:"3 day ...

What is the way to access the Ember global variable 'App' within an Ember CLI application?

As I develop my Ember application with the Ember CLI, I encountered an issue while trying to access the global App variable in order to create and insert a component into my layout. The error message I received was "Uncaught ReferenceError: App is not defi ...

Unique custom babel plug-in - JSXElement traversal not supported

I'm currently in the process of creating my very own babel transform plugin. When I examine the AST for a React component using astxplorer.net, I notice that JSXElement appears in the tree as a node. However, when I attempt to log the path for the vi ...

Inspect the JavaScript file for errors and find a solution to overcome them

Our website's select box has been updated to retrieve city options from a JavaScript array file using an ajax call request. This file is now dynamically created on a different server and then transferred to the static server where it is used to popula ...

Struggling to get the bindings to work in my Angular 2 single-page application template project

I have recently started using the latest SPA template within Visual Studio 2017: https://blogs.msdn.microsoft.com/webdev/2017/02/14/building-single-page-applications-on-asp.net-core-with-javascriptservices/ The template project is functioning properly. ...

Steps for initiating a $.ajax POST request from a client to a server

Currently, I am working on a phonegap application where I need to transfer some data from an HTML file to a server and receive a response in return. Everything works fine when all the files are on the same server. However, once I separate the files between ...

The function and if-else statement are experiencing malfunctions

Currently in the early stages of learning coding, I've been focusing on building a solid foundation by practicing with CodeWars. Utilizing this platform for practice has been beneficial because it offers solutions for guidance. While attempting to wor ...

What causes the return value of keyof to vary in this particular case?

type AppleNode = { type: 'Apple' name: string score: number } type BananaNode = { type: 'Banana' id: number score: number } type FruitNodes = AppleNode | BananaNode type fruitTest = { [P in keyof FruitNodes]: 21 } // Th ...

Updating the content of an SVG file in real-time

I have an SVG file saved externally that includes the following code: <g inkscape:groupmode="layer" id="layer9" inkscape:label="score" style="display:inline"> <text xml:space ...

Using TypeScript or JavaScript, set object keys as fields of a class

I am looking for a way to update the properties of this class dynamically using an object export default class Foo { private accessKey: string; private workspaceId: string; private api: AxiosInstance; public bar: string; public name: s ...

`Running ng serve will result in the creation of a 'dist' folder within each app sub

Since beginning my project, I have encountered an issue that is both normal and frustrating. The dist folder is being created with incomplete information related to the components inside it. dashboard dist (unwanted) components panel dist (unwanted) c ...

Fill in dates in the selection choices for the datepicker

Trying to simplify my issue as much as possible here. Spent hours trying to figure this out. I have a jquery-ui datepicker set up to only display the month and year. I've hidden the calendar on show, with changeMonth, changeYear, and showButtonPanel ...

Encountered an issue with importing a JavaScript library in TypeScript

I am trying to import a JavaScript library called Akarata. I have followed the suggestions from the internet, such as: import * as akarata from 'akarata/dist'; or import * as akarata from 'akarata'; However, I am still encountering ...

Is it possible to generate HTML form fields with fixed positions when using Orbeon forms?

Is there a way in Orbeon forms to position input fields at specific coordinates, relative to a background image? I currently have a paper form that fills an entire page. My goal is to use the scanned image of this form as a background and then overlay inp ...