Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

check if product id already exists in localstorage

guys i have a shopping cart in angular
my code saves the added products in localstorage, I would like my code to be able to access the ‘cart’ and see if the item already exists in localstorage by id

I tried this code, but without success, I would like ideas, who can help me

const retrieverObject: string = localStorage.getItem('cart') || '';
const retrieveObject: Array<any> = retrieverObject ? JSON.parse(retrieverObject) : [];
console.log(retrieveObject)
let presentItem = retrieveObject.find(iteml => iteml.id === item.id);

if (presentItem) {
  console.log('id already exists in localstorage')
} else {
  console.log('id not in localstorage')
}

I think the problem is that I can’t access the cart item array

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

>Solution :

You should take the elements inside the node item inside the localStorage. I could see that your localStorage holds your items inside the key item

Pseudo Code

const retrieverObject: string = localStorage.getItem('cart') || '';
const retrieveObject: Array<any> = retrieverObject ? JSON.parse(retrieverObject)?.item : [];
console.log(retrieveObject)
let presentItem = retrieveObject.find(iteml => iteml.id === item.id);

if (presentItem) {
  console.log('id already exists in localstorage')
} else {
  console.log('id not in localstorage')
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading