I am making a basic js cart with local storage by default the cart is set to [].
sometimes my code works if i reload the page sometimes it dosent.
it works when it feels like it the error is from name1 where i find a object label that is the same as my param
const cart = localStorage.getItem('cart')
const Label = {
strw: 'Strawberry',
choc: 'Chocolate',
van: 'Vanilla'
}
function Addtocart(name:string){
const cartarry = JSON.parse(cart)
const name1 = cartarry.find((element:any)=> element.label === name)
if(name === Label.strw && name1 != undefined || null){
console.log(name1)
return console.log(name)
}else if(name === Label.choc && name1 != undefined || null){
console.log(name1)
return console.log(name)
}else if(name === Label.van && name1 != undefined || null){
console.log(name1)
return console.log(name)
}else{
const template = {
label: name,
quantity: 1
}
cartarry.push(template)
return localStorage.setItem('cart',JSON.stringify(cartarry))
}
}
useEffect(()=>{
if(!cart){
localStorage.setItem('cart',JSON.stringify([]))
}
},[])