Home > Enterprise >  How to check if an id already exists in local-storage
How to check if an id already exists in local-storage

Time:11-18

I want to check if an id already exists or not in local-storage, because I want to display specific button if it does. How can I achieve that?

enter image description here

here is my code

export class FoodPageComponent implements OnInit {

  buttonShow = false;

  food!: Food;
  constructor(
    activatedRoute: ActivatedRoute,
    foodService: FoodService,
    private cartService: CartService,
    private router: Router
    ) {

    activatedRoute.params.subscribe((params) => {
      if(params.id)
      this.food = foodService.getFoodById(params.id);
    })
  }

  ngOnInit(): void {
  }

  addToCart() {
    this.cartService.addToCart(this.food);
    this.router.navigateByUrl('/cart-page');
  }
  

}

CodePudding user response:

Say you have const id = 5 and you want to find item with id === 5 in local storage:

const items = JSON.parse(localStorage.getItem("item"))
let exists = false

for (const item of items) {
    if (item?.food?.id === id) {
        exists = true
        break
    }
}

I based this code on the object structure you provided on the screenshot, so if you ever change that you will have to apply the modifications to the if condition.

CodePudding user response:

Try this:

 ngOnInit(): void {
      let storageItems = localStorage.getItem('item');
      if(storageItems) {
       const items = JSON.Parse(items);
       const requiredItem = items.filter((item)=> item.id == yourId);
      if(requiredItem){
            this.buttonShow = true;
       }
    }    
  }
  • Related