Home > other >  React useEffect() hook not working with JSON.parse,JSON.stringify
React useEffect() hook not working with JSON.parse,JSON.stringify

Time:11-12

I have looked at xy answers to this problem, not a single one helped. I'm creating a simple react app for writing notes for myself. After writing a note I want it to be saved even after refreshing the page. For this I wanted to use useEffect hook, but it doesn't do it and yes its imported from react in header, thank you for any suggestions!

useEffect(() =>{
    const savedNotes = JSON.parse(localStorage.getItem("react-notes-app-data"));

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


useEffect(() => {
    localStorage.setItem("react-notes-app-data", JSON.stringify(notes));

}, [notes]);

I tried useEffect with JSON.parse and JSON.stringify to retrieve data (my note) when refreshing page.

CodePudding user response:

Works for me with that: (as notes update it sets the thing)

function App() {
  const [notes, setNotes] = useState([]);
  useEffect(() => {
    const savedNotes = JSON.parse(localStorage.getItem("react-notes-app-data"));

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

  useEffect(() => {
    localStorage.setItem("react-notes-app-data", JSON.stringify(notes));
  }, [notes]);

  const increase = () => {
    setNotes(['dwd', 'dwd', 'dwd'])
  }
  return (
    <div>
      123
      {notes && notes.map((el) => <div> {el} </div>)}
      <button onClick={increase}>123</button>
    </div>
  );
}

export default App;

CodePudding user response:

Assuming your notes is an array. You should check if there are any items in the array. The useEffect is run when the components render, at that moment the state of notes is still the initial, any empty array. So the localStorage will setItem with the empty array.

useEffect(() => {
  if (notes.length < 1) return;
  localStorage.setItem("react-notes-app-data", JSON.stringify(notes));
}, [notes]);
  • Related