简体   繁体   中英

React, losing saved data in localStorage with useEffect after page refresh

This is probably a noob question, but I'm facing some troubles with the useEffect() hook. I have a Taking Notes App, and I want to make the data persist. I'm using 2 useEffect s: one for when the page is refreshed/loaded by the first time, and other one for when I add a new note to my app.

I putted some logs to check what's happening:

const [notes, setNotes] = useState([
  {
  noteId: nanoid(),
  text: 'This is my 1st note!',
  date: '30/07/2022'
  },
  {
    noteId: nanoid(),
    text: 'This is my 2nd note!',
    date: '30/07/2022'
  }
])

// 1st time the app runs
useEffect(() => {
  const savedNotes = JSON.parse(localStorage.getItem('react-notes'))
  console.log('refresh page call:',savedNotes)

  if(savedNotes) {
    setNotes(savedNotes)
  }
}, [])

//every time a new note is added
useEffect(() => {
  localStorage.setItem('react-notes', JSON.stringify(notes));
  console.log('new note call:', notes)
}, [notes])

The behaviour is a bit strange, because when the page is refreshed the new data is appearing inside the log, but then it disappears, maintaining only the hardcoded data:

在此处输入图像描述

It also makes more calls than I was expecting to. Any thoughts about what is going on here?

Issue

The problem is caused by the below useEffect and how you are initially setting the state:

useEffect(() => {
  localStorage.setItem('react-notes', JSON.stringify(notes));
  console.log('new note call:', notes)
}, [notes])

The above useEffect runs every time notes changes, but also on mount. And on mount the state is equal to that initial array given to useState . So the localStorage is set to that array.

Solution

A solution is to change how you are setting the state as below, so you pick what's in the localStroge if there is something, and otherwise use that initial array you have:

const [notes, setNotes] = useState(
  !localStorage.getItem("react-notes")
    ? [
        {
          noteId: nanoid(),
          text: "This is my 1st note!",
          date: "30/07/2022",
        },
        {
          noteId: nanoid(),
          text: "This is my 2nd note!",
          date: "30/07/2022",
        },
      ]
    : JSON.parse(localStorage.getItem("react-notes"))
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM