How to persist an unshift post request in Angular?

Viewed 57

I am able to unshift my new entry to the top of the array and show it in the UI but when I look at the data, it actually added it to the end anyway (using json-server by the way). This causes the refresh to show it back at the bottom of my list instead of staying up top. Is this a json-server anomaly? I don't recall ever having to doi anything other than unshift and that would work. But I wanted to make sure that I didnt leave anything out.

This is my subscription to the Observable and service

newTask(task: Task) {
  this._taskService.addTask(task).subscribe((task)=>(
    this.tasksCollection.unshift(task)
  ))    
}

If I understand correctly, the back end is responsible for assigning IDs, right? I shouldn't have to do that or sort it either since arrays do not necessarily have to be ordered by IDs

1 Answers

I know unshift mutates the array. Mutation can cause issues with Angular change detection since mutation changes the array without updating the array reference (and Angular can rely on the reference changing to detect a change). Try this instead:

newTask(task: Task) {
  this._taskService.addTask(task).subscribe((task)=>(
    this.tasksCollection = [task, ...this.tasksCollection]
  ))    
}

This will avoid any potential change detection issues.

Related