Eliminating data from an array list in NGXS state management is a simple process

When I was working with NGXS state management, I encountered a problem where attempting to delete a record from the array by its ID resulted in the entire array becoming empty. Below is an example of what my user state looks like:

@State<UserStateModel>({
  name: "users",
  defaults: {
    users: [
      {
        id: 179,
        name: "test",
        email: "test@gmail",
      },{
        id: 190,
        name: "test12",
        email: "test12@gmail",
      }
    ],
  },
})

Here is the delete action implementation:

 @Action(DeleteUser)
  delete(
    { getState, patchState, setState }: StateContext<UserStateModel>,
    { id }
  ) {
    const state = getState();

    setState(
      patch({
        users: state.users.filter((user) => {
          user.id !== id;
        }),
      })
    );
  }

Below is how I trigger the delete action in my component:

export class IndexComponent implements OnInit {
  // users: Observable<User>;

  @Select(UserState.getUsers) users: Observable<User>;

  constructor(private store: Store) {}

  deleteUser(id: number) {
    this.store.dispatch(new DeleteUser(id));
  }
}

Answer №1

After hours of effort, the solution to the problem was finally discovered and resolved. To find the answer, please refer to the NGXS state operator official documentation by clicking here.

The key to resolving this issue lies in the use of the "removeItem" operator.

import {
  patch,
  removeItem
} from "@ngxs/store/operators";
    
export class UserState {
    @Action(DeleteUser)
          delete(
            { getState, patchState, setState }: StateContext<UserStateModel>,
            { id }
          ) {
            const state = getState();
        
            setState(
              patch({
                users: removeItem<User>((user) => user.id === id),
              })
            );
          }
    }

May this solution be of help to you.

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

A guide on activating the <b-overlay> component when a child triggers an Axios request in vue.js

Is there a way to automatically activate the Bootstrap-vue overlay when any child element makes a request, such as using axios? I am looking for a solution that will trigger the overlay without manual intervention. <b-overlay> <child> ...

Unable to find solutions for all parameters in AngularFirestoreDocument: (?, ?)

I have integrated Angular 11 with Firebase for authentication and Firestore for data collection. However, I encountered an error message Can't resolve all parameters for AngularFirestoreDocument: (?, ?). How can I resolve this null injector issue? On ...

Can a form component be recycled through the use of inheritance?

Greetings to the Stackoverflow Community, As I delve into this question, I realize that examples on this topic are scarce. Before diving into specifics, let me outline my strategy. I currently have three pages with numerous FormGroups that overlap signif ...

Integrate Bootstrap 4 with your Angular 6 or Angular 7 application

Currently working on an Angular project that utilizes Bootstrap 4. Seeking assistance with incorporating SCSS into my Angular application. The question at hand is: Are the steps for adding Bootstrap 4 SCSS in Angular 6 and Angular 7 identical? For exa ...

Debugging with Typescript in Visual Studio Code

I attempted to use the solution found here: how to debug typescript files in visual studio code However, when I set a breakpoint in my .ts files, the debugger indicates that the file is not found. Oddly enough, breakpoints in the .js files are working fin ...

What is the correct way to apply type in the .call() method?

I need help finding a solution for the following issue interface IName { name:string; } let obj1:IName = { name: "LINUS" } function profileInfo (age:number,location:string):string{ return `${this.name} is ${age} years old and is from ${location ...

The application is experiencing extended loading times during production

After deploying my Angular 2 app on Heroku, I've noticed that it's taking a long time to load. Is there a way to bundle everything up instead of having all the scripts and stylesheets scattered across my index.html file? <html> <head> ...

I want to use Angular and TypeScript to play a base64 encoded MP3 file

I am attempting to play a base64 encoded mp3 file in an Angular application. I have a byteArray that I convert to base64, and it seems like the byte array is not corrupted because when I convert it and paste the base64 string on StackBlitz https://stackbli ...

What is the proper way to reference a computed symbol that has been inherited as a function in an extended class

As a newcomer to Typescript, my understanding of the code might be lacking. I am currently working with the Klasa framework, which is built on top of Discord bot framework using Discord.js. The framework recently introduced plugin functionality and there a ...

Error encountered during Angular ahead-of-time (AOT) compilation: Internal state issue - Summaries cannot contain members in StaticSymbols

Our team is currently working on implementing ahead of time (AOT) compilation for our Angular 2 project, but we have encountered an error: Error: Internal state: StaticSymbols in summaries can't have members! {"filePath":"C:/Users/bhavy/Documents/p ...

NPM: There are no valid TypeScript file rules specified

Currently working on a small project using React.JS. Whenever I execute : npm run start, the following message gets logged: Starting type checking and linting service... Using 1 worker with 2048MB memory limit Watching: /Users/John/Projects/myProject/src ...

Can data from an Angular app be accessed by an external JavaScript code within the same project?

I've been thinking about a theoretical scenario that luckily I haven't encountered yet. Imagine I have an Angular Project compiled in My PROJECT FOLDER. <br/> Inside this PROJECT FOLDER, there's another JAVASCRIPT FILE external to ...

Middleware in Redux Toolkit is ineffective in managing successful asynchronous actions

After integrating my own middleware into the Redux-Toolkit store using configureStore in my Next.js app, I noticed that the middleware functions appear to be greyed out. I added them via: getDefaultMiddleware({ thunk: { extraArgument: updateNavTabMid ...

Enhance React components in Deck.GL by including default properties for each child component

I am currently working on a customizable collection of map layers using Deck.GL & React. I have developed a BaseMap component through which I will be passing data layers as react children. This is the current implementation: BaseMap: export const BaseMap ...

Effortless transfer of a module from one TypeScript file to another

I'm facing an issue with importing classes from one .ts file to another .ts file. Here is the structure of my project: https://i.sstatic.net/gZM57.png I'm attempting to import print.ts into testing.ts This is how my tsconfig.json appears: ht ...

How to utilize TypeScript fetch in a TypeScript project running on node with Hardhat?

During a test in my hardhat project on VSCode, I encountered the need to retrieve the metadata object of my NFT from a specified URL. Initially, I assumed I would have to import fs to read the URL. However, while typing out the method, I impulsively opted ...

Trouble arises in TypeScript when defining a class - SyntaxError crops up

When I try to declare a class, I encounter an error: // The code below is from my test1.ts file class WDesign { wModel: string; wQuer: string; } let logWDesign = (wd : WDesign) => { console.log(wd.wModel + " " + wd.wQuer); } let wd1 : WDe ...

Update constant data returned from Angular2 service

Issue at Hand: I am facing an issue where I want to store default data in a separate file so that I can easily reset the default value when needed. However, the Const Data seems to be getting updated. I could simply hardcode the value directly into the co ...

Angular repeatedly triggering cloud function

Currently facing an issue in my angular project where a cloud function is being triggered multiple times. The console.log('call') statement is appearing three times. this.profileList$ = this.usersService.profileList(this.route.snapshot.paramMap.g ...

What could be the reason for the failure of running `npm install -g @angular/cli`

https://i.sstatic.net/wsjDI.png Attempting to set up angular/cli through the command prompt, using node.js version 8.1.2 ...