Conor Donohoe
Conor Donohoe

Reputation: 317

How do you update a value in local Storage array Angular 7

What I am trying to do is update a single value in an array this is the code I have so far for it but it doesn't seem to be working correctly, was wondering if anyone would be able to help me with this.

So, how I think it works is it takes the index position from the ngFor as well as the auto-incrementing id for the array makes sure it has a match and pushes the new name to the array.

But that doesn't seem to be working, it executes the toastr to say it has been updated but it hasn't in the Local Storage

     public updateNameLocalStorage(Name, id, i ): void {
          const currentArray = this.storage.get(this.STORAGE_KEY);
          console.log(currentArray);
          for (i = 0; i < currentArray.length; ++i) {
               if (currentArray[i].id === id) {
                    currentArray.push({
                         Name: Name
                     });
                     // insert updated array to local storage
                     this.storage.set(this.STORAGE_KEY, currentArray);
                     this.notifiy.showInfo('Name Updated'  , '');
                } else {
                    this.notifiy.showFailure('Error'  , '');

                }

          }

This is the structure of the data

enter image description here

Upvotes: 0

Views: 1095

Answers (1)

Fussel
Fussel

Reputation: 1865

You are using push which appends an element to the end of an array. If you want to update a value with the given ID just access the index directly and override the value. Also if you just push {Name: Name} the object in the array has no property id anymore.

Something like this:

const currentArray = this.storage.get(this.STORAGE_KEY);
const index = currentArray.findIndex(e => e.id === id);
if(index >= 0) {
  currentArray[index] = {...currentArray[index], ...{Name:Name}}; 
  this.storage.set(this.STORAGE_KEY, currentArray);
  this.notifiy.showInfo('Name Updated'  , '');
} else {
  this.notifiy.showFailure('Error'  , '');
}

Upvotes: 1

Related Questions