TransWikia.com

How can I access certain element's key in local storage?

Stack Overflow Asked by D.Aktas on January 23, 2021

I have an array of objects like this and when I click the Remove Favorite button I want to delete the certain element from local storage. I’m deleting from the page with the removeLocal() function but it only deletes from the page, not from local storage. I want to delete it both. I’m generating random number when assigning local storage key. Is there way to access this key and delete the item?

enter image description here
enter image description here

html:

<input type="text" [(ngModel)]="profile" (ngModelChange)="detectChange($event)" (keyup)="findProfile()"
  placeholder="Enter the username..." class="input">
<div style="background-color: lightslategrey;">
  <ng-template [ngIf]="profile !== '' && user">
    <img [src]="user.avatar_url" alt="" class="userAvatar">
    <p>Username: {{user.login}}</p>
    <p>Location: {{user.location}}</p>
    <p>E-mail: {{user.email}}</p>
    <p>Blog Link: {{user.blog}}</p>
    <p>Member Since: {{user.created_at}}</p>
    <button [routerLink]="['', user.login.toLowerCase(), user.id ]" class="viewProfileButton" a>View
      Profile</button><br>
    <button (click)="localStorage()" class="viewProfileButton">Add to Favorite</button>
  </ng-template>
</div>

<div *ngIf="closeDiv">
  <div style="background-color: rgb(106, 106, 170);" *ngFor="let item of display">
    <p>Username: {{item.login}}</p>
    <p>Location: {{item.location}}</p>
    <p>ID: {{item.id}}</p>
    <button (click)="removeLocal(item.id)" class="viewProfileButton">Remove Favorite</button>
  </div>
</div>

<button (click)="consoleLog()" class="viewProfileButton">Console Log</button>
<router-outlet></router-outlet>

ts:

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss'],
})
export class HomeComponent implements OnInit {
  user: any;
  profile: any;
  display: any;
  local: any;
  randomNumber: any;
  randomString: any;
  idString: any;
  keys: any;
  closeDiv: boolean = true;
  constructor(private userData: HttpService) {}

  ngOnInit() {
    this.display = Object.values(localStorage).map((val: any) => JSON.parse(val));
    console.log('ngOnInit Works', this.display);
  }

  findProfile() {
    this.userData.updateProfile(this.profile);
    this.userData.getUser().subscribe((result) => {
      this.user = result;
    });
  }

  localStorage(id: any) {
    this.randomNumber = Math.floor(Math.random() * 10000);
    this.randomString = this.randomNumber.toString();
    localStorage.setItem(this.randomString, JSON.stringify(this.user));
    this.display = Object.values(localStorage).map((val: any) => JSON.parse(val));
    console.log(this.display);
  }

  removeLocal(id: any) {
    for (let i = 0; i < this.display.length; i++) {
      if (this.display[i].id === id) {
        this.display.splice(i, 1);
      }
    }
  }

  detectChange(ev: any) {
    ev.length > 0 ? (this.closeDiv = false) : (this.closeDiv = true);
  }

}

One Answer

Add the call localStorage.removeItem(key) to your removeLocal function. Granted, you need to store your random keys somewhere, otherwise you will have to integrate this solution to parse through them.

  removeLocal(id: any, key: string) {
    for (let i = 0; i < this.display.length; i++) {
      if (this.display[i].id === id) {
        this.display.splice(i, 1);
        localStorage.removeItem(key); // here
      }
    }
  }

EDIT: After a conversation in the comments, this solution can be simplified to remove a variable from the function header by storing a storageKey variable within display.

  removeLocal(id: any) {
    for (let i = 0; i < this.display.length; i++) {
      if (this.display[i].id === id) {
        localStorage.removeItem(this.display[i].storageKey);
        this.display.splice(i, 1);
      }
    }
  }

Correct answer by rhavelka on January 23, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP