After a create, update an array with data from a get or increment the Response in the array?

Asked

Viewed 57 times

-2

Assuming I have a table showing data from an array, when entering a new element in the database via a request POST, how best to update the data on screen?

I’m always in doubt between making a GET again, to then include the new records:

this.service.save(element).subscribe(res => {
  this.getLista()
});

In this way I believe that it has the advantage of inserting beyond the element that has just been created, the element that other people created between the moment of the save and the call from get but it would be an extra request and depending on the amount of data.

or take the return of the api, which is usually the element that was created, and insert into the arrray:

this.service.save(element).subscribe(res => {
  this.array.push(res.data)
});

This way adds instantly without depending on the server, but it may be that the list is not fully updated.

Which of the two ways is the most recommended to update data that has just been added/deleted/updated?

  • 1

    Your question face is wide and mainly depends on each case, I always do a get to make sure to pick up all the changes, the second way do not know if you would be with the list 100% updated, only that would do different, I would do the get on ngOnInit() and in the post if all goes well then I give a ngOnInit() to reload and update the component

1 answer

-1

Friend, this question can be quite explored, you can use state control to do this. There are some libraries available.

ngxs ngrx

You would trigger the actions that would update your lists.

You can use rxjs itself, creating a "service Singleton" that shares your Subject or Behaviorsubject, where the components would give a next in the span, triggering the updates to your list, between components.

Subject behaviorsubject

Take a look at the solutions and use the one that best fits your problem

  • my question is the best way to update the list, for example, an action that performs a get() to bring the records or an action that I send the new created object and it updates the array

  • 1

    So, there are several ways to do, all are valid, have to see what fits best n your problem, you create a service that updates the list using rxjs is the easiest and fastest means, where the main list that is presented is listening to the service Subject, when you pick up the return of get, it triggers a setNewItem, it has the next value of the service, automatically the list presents the data, saying that you are working with multiple components, in a Component just would not make sense

  • 1

    And with state control, you would know if the item was changed or not, if the lists were identical, there would be no triggering of actions

Browser other questions tagged

You are not signed in. Login or sign up in order to post.