Search code examples
angulartypescript

Good Practice for Updating Client-side Data after CRUD Operations with Angular and API Requests


I'm developing an Angular application that communicates with a server via API requests.

I have a component that stores a collection of objects received from the server. And currently, after each CRUD operation (create, read, update, delete), I'm fetching the entire collection of objects from the server again that includes this modieed/added object.

So, my question is:

Is it considered a normal practice to fetch the entire collection of elenets from the server after each CRUD operation or it would be better to locally update the client-side collection with the modified/added object.

Sample code below.

Thank you.

class SampleComponent {

    collection: any = [];

    constructor(private sampleService: SampleService) {
    }

    // Approach 1
    addElement(newElement: any) {
        this.sampleService.addElement(newElement).subscribe(e => {
            this.sampleService.findAllElements(collection => this.collection = collection);
        });

    }

    // Approach 2
    addElement(newElement: any) {
        this.sampleService.addElement(newElement).subscribe(e => {
            this.collection.push(e);
        });
    }
}

Solution

  • Think about a scenario where your app has multiple users, each will perform crud operations, so

    Scenario: Manager informs team to update at least 10000 billing amount to one of the rows.

    1. User 1 and User 2 open the screen simultaneously
    2. User 1 updated billing amount to 10000 of row 1
    3. User 2 updated billing amount to 10000 of row 2

    When user 2 has the logic of updating only one row. I will look like user2 was the first person to refresh the amount to 10000, even though user1 executed it first!

    When user 2 has the logic of refreshing the entire table. It will reflect that user 1 already performed an update on one row for 10000, so user 2 can revert their update.

    So long story short, refresh the entire dataset to avoid stale data being shown to the end user!

    We can also update the realtime updates using websockets and other technologies, but above method is the simplest solution I feel