-1

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);
  }

}
D.Aktas
  • 38
  • 1
  • 6

1 Answers1

0

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);
      }
    }
  }
rhavelka
  • 2,283
  • 3
  • 22
  • 36
  • I tried it but key parameter is undefined. I guess I should send the parameter from html right? – D.Aktas Aug 03 '20 at 15:33
  • yes, but before you pass in the parameter, you need to store it some where. something like `this.user.storageKey = this.randomString` before you set it in localStorage, so it would have to be in your `localStorage()` function. Otherwise you are abandoning them. – rhavelka Aug 03 '20 at 15:36
  • @DAktas I updated my solution with a a second option, just to simplify things a little more. – rhavelka Aug 03 '20 at 16:11