Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

116
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!