Issue with TypeScript causing missing data upon user deletion

I am currently using the Chrome browser and working on a project involving a table listing users. I have implemented CRUD functionalities for this table. However, when trying to delete a user, sometimes the data reloads successfully, but other times it does not reflect the changes immediately (requiring a page refresh with F5 to display the latest data).

 deleteUser(user: User) {
    if(user){
      this.userService.deleteUser(user);
      this.ngOnInit();
    }
  }

 ngOnInit() { // Fetch all users and populate the users[] array when the component loads
    this.getAllUsers();  
  }

 getAllUsers() {
    this.userService.getUsers().then(users =>
        this.users = users
       );

  }

Service:

deleteUser(user: User): Promise<void> {
        const url = `${this.userUrl}/${user.id}`;
        return this.http.delete(url, { headers: this.headers })
          .toPromise()
          .then(() => null)
          .catch(this.handleError);
      }

 getUsers(): Promise<User[]> {
        return this.http.get(this.userUrl)
          .toPromise()
          .then(response => response.json().content as User[])
          .catch(this.handleError)
      }

HTML:

<button  type="button" class="btn btn-warning" (click)="deleteUser(user)">Delete</button>

Please provide any advice or suggestions you may have. Thank you.

Answer №1

Here is the recommended approach:

async removeUser(user: User): Promise<void>  {
    if(user){
      await this.userService.removeUser(user);
      await this.fetchAllUsers();
    }
}

Please note that manually invoking the ngOnInit hook is not ideal, as ngOnInit does not return a promise. This can lead to race conditions when removeUser is triggered by other methods aside from the click event (such as during testing).

Answer №2

Rather than

this.userService.deleteUser(user);
this.ngOnInit();

You could try

this.userService.deleteUser(user).then(res => this.ngOnInit());

Answer №3

removeUser(user: User) {
    if(user){
      this.userService.removeUser(user)
           .then(() => this.refreshComponent());
    }
  }

Make sure to wait for the promise to be resolved before calling the refreshComponent function in the removeUser service.

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

Issue encountered with dynamic ngStyle variable: ERROR Error: Unable to locate a supporting object 'ngStyleSmall'

I have defined two variables for ngstyle ngStyleSmall = { width: '150px !important', 'max-width': '150px', }; ngStylemedium = { width: '250px !important', 'max-width&apo ...

What steps can I take to guarantee that the observer receives the latest value immediately upon subscribing?

In my Angular 2 and Typescript project, I am utilizing rxjs. The goal is to share a common web-resource (referred to as a "project" in the app) among multiple components. To achieve this, I implemented a service that provides an observable to be shared by ...

Is the tooltip display for Typescript types in VSCode reliable? No need for unnecessary type assertions

Exploring the concept of const assertions in TypeScript Looking at the array allDeviceTypes depicted below, VSCode indicates it has a return type of string[] when hovering over the variable name. https://i.sstatic.net/gIYch.png However, upon using a con ...

The MUI datagrid fails to display any rows even though there are clearly rows present

Today, I encountered an issue with the datagrid in Material UI. Despite having rows of data, they are not displaying properly on the screen. This problem is completely new to me as everything was working perfectly just yesterday. The only thing I did betwe ...

Differences between Typescript, Tsc, and Ntypescript

It all began when the command tsc --init refused to work... I'm curious, what sets apart these three commands: npm install -g typescript npm install -g tsc npm install -g ntsc Initially, I assumed "tsc" was just an abbreviation for typescript, but ...

What is the best way to create a dynamic string based on a list's contents?

To create a personalized message, I am looking to generate a string based on user input and then loop through a list of first names. For instance: Given a list of first names: let firstnameList = ["Jan", "Mark","Doe"] And a message entered by the user: ...

Is there a way to prevent the splash screen from appearing every time I navigate using a navbar link in a single page application (SPA)?

Recently, I came across this tutorial and followed it diligently. Everything seemed to be working perfectly until I encountered an issue with my navbar links. Each time I clicked on a link, the splash screen appeared, refreshing the page without directing ...

Trouble Downloading CSV with Japanese Characters from Backend in Angular 9

I am trying to accomplish the following: when a user clicks on a download link, a CSV file containing Japanese characters should be generated dynamically from a Laravel backend and automatically downloaded to the user's PC. Issue: The CSV file displa ...

Dynamically incorporating validation to an ngModel input

Utilizing NgForm, I dynamically added a validator to the input field. In my first example, everything works perfectly when I use the button setValidation to validate the input. However, in the second example where I add formGroup, I encounter an error whe ...

Set an enumerated data type as the key's value in an object structure

Here is an example of my custom Enum: export enum MyCustomEnum { Item1 = 'Item 1', Item2 = 'Item 2', Item3 = 'Item 3', Item4 = 'Item 4', Item5 = 'Item 5', } I am trying to define a type for the f ...

ng2-select is experiencing difficulties when attempting to retrieve and process data from an API while also casting it within the initData

Issue with ng2-select and API Data Retrieval I am encountering a problem while using ng2-select in my form. I am fetching data from an API and setting it into an array, but it is not functioning correctly. Below is the code snippet I am working with. When ...

Allow only numerical values through an ion-input in Ionic 4, preventing the input of letters and special characters

I am currently developing an application in Ionic 4 that requires users to enter only integer numbers (0-9). I need to prevent any other characters such as alphabets, dots, or plus signs from being entered. However, the methods I have tried so far have not ...

When using React with TypeScript, the error message "No overload matches this call" may indicate a mismatch

I encountered the error shown in screenshot error_2 https://i.sstatic.net/HpO7L.jpg Here, I have imported AgGridReact from the ag-grid-react library at the beginning of my code. I am unsure how to declare an interface for AgGridReact since it is not a comp ...

Setting the minDate of an ngbDatepicker programmatically using the current date

I am attempting to set the minimum date of a ngbDatepicker as today's date. In the component logic, I have the following setup: export class ShareLinkFormComponent implements OnInit { minPickerDate = "{year: " + new Date().getFullYear() + ", mont ...

Steps for building a custom component using MUI as a foundation

My current approach: import React from "react"; import {useHistory} from "react-router-dom"; import {Button, ButtonProps} from "@mui/material"; type Props = { label?: string } & ButtonProps; export const NavBackButton = ...

Incorporating a JSF page within an Angular application: A comprehensive guide

I have two different applications, one built using JSF and the other with Angular. I am currently exploring ways to call the JSF application from within the Angular application. While I have found one potential solution, I am searching for alternative meth ...

Guide to adding annotations to a PDF document using Angular 2

As a novice in the field of Angular development, I am seeking guidance. Currently, I have an application that displays PDF files. My goal is to be able to annotate and make changes on these PDF files by adding drawings such as circles, lines, or text. Ho ...

Issues arise when attempting to utilize Async/Await with a gRPC method

Here is the code snippet used to initialize a gRPC server: export const initServer = async (finalPort: number): Promise<string> => { let initStatus = 'initial'; gRPCserver.addService(webcomponentHandler.service, webcomponentHandler.h ...

Having trouble getting Edge browser to identify embedded blob as a valid source URL within a video tag

Having trouble using a blob as the source for a video file. Works well on Chrome and Safari, but facing issues on Edge. This code is written in TypeScript with Angular 7. On Edge mobile, it seems like a broken link is displayed. private initVideoFromBlo ...

The type 'Requireable<string>' cannot be matched with the type 'Validator<"horizontal" | "vertical" | undefined>'

code import * as React from 'react'; import * as PropTypes from 'prop-types'; interface ILayoutProps { dir?: 'horizontal' | 'vertical' }; const Layout: React.FunctionComponent<ILayoutProps> = (props) => ...