Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

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

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>
  );
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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)
    }
  }, []);
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda