i am looking to save the customer product selection in basket and to avoid the effect of refesh
of page i am also saving the customer selection to local storage, i am use spread ....prevItems
and using window.localStorage.setItem
,but as prevItems initial value is null
so it comes up with an error of TypeError: prevItems is not iterable
, i have tried passing the product,quantity to initial value(to make to iterable afterwards) but the initialvalue= callback
is present outside the main function and was unsuccessful. Not sure what else i can do to overcome this issue.
Any suggestions guys.
let initialvalue = () => {
return window.localStorage.getItem("user-basket", {});
};
function App() {
const [basketItems, setBasketItems] = useState(initialvalue());
// basketItems will be like[{Product1},{Product2}, and so on...] i.e it will store each product as a new object
const addBasketitems = (product, quantity) => {
setBasketItems((prevItems) => {
console.log("prevItems", prevItems);
console.log("product", product);// the product customer selected
console.log("quantity", quantity);// no. of item of a product customer selected
const newItems = [...prevItems, { ...product, quantity }];
window.localStorage.setItem("user-basket", JSON.stringify(newItems));
return newItems;
});
<Router>
<Switch>
<Route
path="/"
exact
render={(props) => <Home {...props} userData={userData} userstatus={siginalready} addBasketitems={addBasketitems}
/>}
</Switch>
</Router>
```