Mr. Mars
Mr. Mars

Reputation: 840

Angular CRUD - Refresh UI after add/update/delete operation

I was wondering that it is better to refresh the UI when executing an add/update/delete operation from a CRUD in Angular.

The options are as follows (for example, for delete action):

1. Update local variable with previously fetched data after perform the action.

deleteProduct(id) {
    this.productsService.deleteProduct(id).subscribe(status => {
        this.products = this.products.filter(item => item.id != id);
    });
}

2. Fetch the items again calling REST API.

deleteProduct(id) {
    this.productsService.deleteProduct(id).subscribe(status => {
        this.getProducts();
    });
}

getProducts() {
    this.productsService.getProducts().subscribe(products => {
        this.products = products;
    });
}

This would also be applicable to add or edit, with more code obviously.

Which option is better in terms of good practices and performance? Updating variable data locally or performing a new http request to obtain updated data.

Upvotes: 3

Views: 2067

Answers (3)

Abolfazl Roshanzamir
Abolfazl Roshanzamir

Reputation: 14802

I think, It can depend on your project . I use the following flow in my project (client[Angular] should follow the server)

(Here I use WEB API)

To create : It's better to return the created Item as below

[HttpPost]
public ActionResult Post(Item item)
{
    if (everything is ok)
    {
        // resourceUrl: the address of the source that we have just created
        return Created(resourceUrl, item);
    }

    if (there is an error) {
        return BadRequest();
    }
}

To Edit : You do not need to return any Item, you should return the status code (400[BadRequest], 200[OK], 204[NoContent] and so on) like the following :

[HttpPut("{id}")]
public ActionResult Put(Item item, int id)
{
    var existingItem = (retrive item form db based on id); 
    if (existingItem == null) {
        return BadRequest("Cannot update ...");
    } else {
        // update operation here ...
        return Ok();
    }
}

To delete - you should return the status code (400[BadRequest], 200[OK], 204[NoContent] and so on)

EDIT:

You don't have to follow above recommendation. You can select the first suggestion in your question (Update local variable with previously fetched data after perform the action.) , It depends on your project.

Upvotes: 1

MoxxiManagarm
MoxxiManagarm

Reputation: 9124

I think it depends on your application.

Obviously the first approach is one less api call and is faster.

But imagine you have a high frequency of operations on the backend data by other users. In that case it could be very useful to refresh the list after an operation.

Upvotes: 1

Hiras Haris
Hiras Haris

Reputation: 498

The first approach is more preferred, it is less time consuming than the second option so low loading time.

Upvotes: 1

Related Questions