Home:ALL Converter>Unable to persist state of a cart (ecommerce website) in localstorage

Unable to persist state of a cart (ecommerce website) in localstorage

Ask Time:2022-06-25T17:10:29         Author:randomsizzler

Json Formatter

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>
  );
}

Author:randomsizzler,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/72752626/unable-to-persist-state-of-a-cart-ecommerce-website-in-localstorage
yy