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

111
Views
Why useEffect doesn't set items from local storage?

I've started to learn web development recently and this is making my head hurt. I made a simple todo app where you can add an item with id and value to an array and delete the item from the array. Now I want whenever the site refreshes, I want the items to be there. I made a testing array and for some reason, when refreshed, it works but not with data.

  const [items, setItems] = useState([]);
  const testarr = [{id: 1, value: "a"}, {id: 2, value: "b"}];

  useEffect(() => {
    const data = JSON.parse(localStorage.getItem("items"));
    console.log(data);
    // setItems(testarr);
    setItems(data);
  }, [])

  useEffect(() => {
    window.localStorage.setItem("items", JSON.stringify(items));
  }, [items]);

What I came up with:

  useEffect(() => {
    const data = JSON.parse(localStorage.getItem("items"));
    data.forEach(element => {
      setItems(oldarr => [...oldarr, element]);
    });
  }, [])

The problem is, if I keep refreshing the site fast enough, eventually the array will become empty again. I don't understand, when refreshed it logs data just fine but when I want to setItems(data) that doesn't work. Does anyone know why it behaves like this?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

setState is an asynchronous function, this implies that this code snippet below will always run with items as empty arrays before items receive data from "setItems(data)".

    useEffect(() => {
       window.localStorage.setItem("items", JSON.stringify(items));
    }, [items]);

maybe, you can check if items isn't a empty array before store

    useEffect(() => {
       if (Array.isArray(items) && items.length > 0) {
           window.localStorage.setItem("items", JSON.stringify(items));
       }
    }, [items]);
about 4 years ago · Juan Pablo Isaza Report

0

Please try localStorage without window Object

For example:

useEffect(() => {
    localStorage.setItem("items", JSON.stringify(items));
  }, [items]);
about 4 years ago · Juan Pablo Isaza Report

0

Issue

The below useEffect runs every time items changes, but also on mount. And on mount items is equal to [], that array given to useState in the beginning. That's why the localStorage is being set to [].

useEffect(() => {
 window.localStorage.setItem("items", JSON.stringify(items));
}, [items]);

Solution

One way to solve this issue is to change your state definition as below, so when there is data in the localStorage you pick it:

const [items, setItems] = useState(!localStorage.getItem("items") ? [] : JSON.parse(localStorage.getItem("items")));

And at this point, you can remove those two useEffects you have there for getting data from the localStorage and giving it to setItems.

about 4 years ago · Juan Pablo Isaza 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!