i am working on eCommerce project , i am currently facing a problem where as user clicks on add to cart button the code setCart([...cart,item]) runs since the initial state of cart is empty array like const [cart,setCart] = useState([]) therefore as i try to save it on localstorage it gives me empty array and then start saving data in second array
code:
const [cartValue,setCartValue] = useState(0)
const [cart,setCart] = useState([])
const cartValueIncreaserandSetter = (item) =>{
setCart([...cart,item])
setCartValue(cartValue+1)
localStorage.setItem("items",JSON.stringify(cart))
}
i want the localstorage to immediately save the first item added but the localstorage gives [] array on first click on add to cart
When you have side effect in your code (which is the case when you manipulate the localstorage) you should use the useEffect
hook.
I suggest you to rewrite your code like this :
const [cartValue,setCartValue] = useState(0)
const [cart,setCart] = useState([])
const cartValueIncreaserandSetter = (item) => {
setCart([...cart, item])
setCartValue(cartValue+1)
}
useEffect(() => {
localStorage.setItem("items",JSON.stringify(cart))
}, [cart]);