I am trying to persist the state of the items in my cart with the help of local storage. While I am able to save the items in the local storage when an item is added, the cart does not persist when I refresh the page.
I am lost as to where in this code should I implement the "getItem" code to persist the state cart even the page is refreshed. Any help would be appreciated, attaching the code files below.
CartProvider.js
import React from "react";
import CartContext from "./cart-context";
import { useReducer, useEffect } from "react";
const defaultCartState = {
items: [],
totalAmount: 0,
};
const cartReducer = (state, action) => {
let updatedItem;
let updatedItems;
if (action.type === "ADD_CART_ITEM") {
updatedItem = { ...action.item };
updatedItems = state.items.concat(action.item);
}
const newTotalAmount = state.totalAmount + action.item.price;
const localData = localStorage.getItem("cart");
return {
items: updatedItems,
totalAmount: newTotalAmount,
};
};
export default function CartProvider(props) {
const [cartState, dispatchCartAction] = useReducer(
cartReducer,
defaultCartState
);
const addItemToCartHandler = (item) => {
dispatchCartAction({ type: "ADD_CART_ITEM", item: item });
};
const removeItemFromCartHandler = (id) => {
dispatchCartAction({ type: "REMOVE_CART_ITEM", id: id });
};
const cartContext = {
items: cartState.items,
totalAmount: cartState.totalAmount,
addItem: addItemToCartHandler,
removeItem: removeItemFromCartHandler,
};
useEffect(() => {
localStorage.setItem("cart", JSON.stringify(cartState.items));
}, [cartState.items]);
return (
<CartContext.Provider value={cartContext}>
{props.children}
</CartContext.Provider>
);
}
declare useEffect
with no dependency so it will only run once through component life cycle at that time you can check if data exists in localstorage than you set it , check below example.
useEffect(() => {
let items=JSON.parse(localStorage.getItem("cart"));
if(items){
addItemToCartHandler (items)
}
}, []);