I'm trying to save products from shopping cart to local storage, but on page refresh it does not work like it suppose to. When I refresh page, products are in shopping cart, but soon as I add new item, it gets erased. Also, deleting product deletes everything, not the specific one when using local storage. This is what I tried:
in App.tsx set array
const [productList, dispatch] = useReducer((state: any, action: any) => {
switch (action.type) {
case "ADD_ITEM":
const noDoubleItems = state.filter((item: any) => item.id !== action.payload.id);
localStorage.setItem("cart",JSON.stringify([...noDoubleItems, action.payload]));
return [...noDoubleItems, action.payload];
case "DELETE_ITEM":
localStorage.setItem("cart", JSON.stringify(state));
return state.filter((item: any) => item.id !== action.payload.id);
default:
return state;
}
}, []);
in Cart.tsx get array
const storageCart = localStorage.getItem("cart");
const storageCartObject = storageCart && JSON.parse(storageCart);
Here is code sandbox: https://codesandbox.io/s/flamboyant-torvalds-tevby?file=/src/components/pages/Cart.tsx:298-1026