I'm trying to create a shopping cart, in 1 component the items are added to the shopping cart that places this data in the localstorage.
The shopping cart component looks like this, first with this code:
useEffect(()=>{
SaveToShoppingbag();
},[])
SaveToShoppingBag() , looks like this:
let SaveToShoppingbag = () =>{
if(JSON.parse(localStorage.getItem('Shoppingbag')) != null){
SetShoppingbag(JSON.parse(localStorage.getItem('Shoppingbag')))
}
}
Based on that, the following useEffect is triggered:
useEffect(()=>{
SetTotalPrice(0)
TotalPrices= []
CalculatePrice()
},[Shoppingbag])
Price calculations are correct. If a number of the product changes in the component, this is also neatly settled. Only when I add a product to the shopping cart from the other component (localstorage.getItem('shoppingbag') ) it is not added, which is probably due to the ,[] in the useEffect. However, if I omit this, the price continues to count because it responds to a change in the shopping bag (,[Shoppingbag])
So anyone have a solution? What if an item is added to the localstorage that the useEffect reacts to?
What I've already tried is to add an eventlistner('storage') but the browser doesn't respond to that because it probably has to do with SSR because I'm using NextJS.