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

111
Vistas
LocalStorage is empty in the 1st render NEXT.js

Im creating a shopping cart with NextJS and it works, but when I try to console log the length of my cart, in the first render it appears empty so it gives me a bunch of problems.

    const initialState = {};
  const [cart, setCart] = useState(initialState);

  useEffect(() => {
    const cartData = JSON.parse(localStorage.getItem("cart"));
    if (cartData) {
      setCart(cartData);
    }
  }, []);  

  useEffect(() => {
      localStorage.setItem("cart", JSON.stringify(cart));

  }, [cart]);

All cart methods such as DeleteCart, AddToCart, etc work fine. Any idea?

almost 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

You are 'almost' looping these two useEffect. Try this:

  const initialState = {};
  const [cart, setCart] = useState(initialState);

  useEffect(() => {
    const cartData = JSON.parse(localStorage.getItem("cart"));
    if (cartData) {
      setCart(cartData);
    }
  }, []);  

  useEffect(() => {
      if(Object.keys(cart).length > 0){
          localStorage.setItem("cart", JSON.stringify(cart));
      {
  }, [cart]);
almost 4 years ago · Santiago Trujillo 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