Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

170
Visualizações
Simple Notes App Not Working With Local Storage

I have a bare bones project that displays a list of notes and a button that will add a new note to that list to be displayed. My issue is that the new notes are not added/retrieved from local storage and I'm not sure what is causing it.

import React, { useEffect, useState } from 'react'
function App() {

  const [notesList, setNotesList] = useState([])

  useEffect(() => {
    const notesJSON = localStorage.getItem('ayo')
    if (notesJSON != null) setNotesList(JSON.parse(notesJSON))
    console.log(notesList)
  }, [])

  useEffect(() => {
    localStorage.setItem('ayo', JSON.stringify(notesList))
  }, [notesList])

  function addNote(e) {
    e.preventDefault()

    const newNote = {
      id: Date.now() + Math.random(),
      text: 'this is a new note',
      status: false,
    }
    setNotesList([...notesList, newNote])
  }

  return (
    <>
      <h1>Hello</h1>
      {notesList.map((note) => {
        return <h1 key={note.id}>{note.text}</h1>
      })}
      <form onSubmit={addNote}>
        <button type='submit'>Add Note</button>
      </form>
    </>
  )
}

export default App;
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Just remove the console log from the first useEffect where we retrieve data from localStorage and where we update notesList state if there is data previously stored in it. For logging purposes, add a button to check the data that is stored in the localStorage like below.

We can'not watch the changes of localStorage by using useEffect with deps notesList. If you try, you will always get data that one step behind the notesList state value.

import React, { useCallback, useEffect, useState } from "react";

export default function App() {
  const [notesList, setNotesList] = useState([]);

  useEffect(() => {
    const notesJSON = localStorage.getItem("ayo");
    notesJSON && setNotesList(JSON.parse(notesJSON));
  }, []);

  // this will always log the data that one step behind the notelist state
  useEffect(() => {
    const notesJSON = localStorage.getItem("ayo");
    notesList && console.log(JSON.parse(notesJSON));
  }, [notesList]);

  useEffect(() => {
    if (notesList.length > 0) {
      localStorage.setItem("ayo", JSON.stringify(notesList));
    }
  }, [notesList]);

  const addNote = useCallback(() => {
    const newNote = {
      id: Date.now() + Math.random(),
      text: "this is a new note",
      status: false,
    };
    setNotesList([...notesList, newNote]);
  }, [notesList]);

  const resetNote = () => {
    localStorage.setItem("ayo", JSON.stringify([]));
    setNotesList([]);
  };

  const logNote = () => {
    console.log(localStorage.getItem("ayo"));
  };

  return (
    <>
      <h1>Hello</h1>
      {notesList.map((note) => {
        return (
          <div key={note.id}>
            <h1>{note.text}</h1>
            <p>{note.id}</p>
          </div>
        );
      })}
      <button onClick={addNote}>Add Note</button>
      <button onClick={resetNote}>Reset Note</button>
      <button onClick={logNote}>Log Note</button>
    </>
  );
}

about 4 years ago · Juan Pablo Isaza Relatório

0

The second useEffect is unnecessary, you should set the appended list to your state and the storage in the addNote function and the first useEffect hook should be used to load your initial state and that's it.

import React, { useEffect, useState } from "react";
function App() {
  const [notesList, setNotesList] = useState([]);

  useEffect(() => {
    const notesJSON = localStorage.getItem("ayo");
    if (notesJSON != null) {
      setNotesList(JSON.parse(notesJSON));
    }
  }, []);

  function addNote(e) {
    e.preventDefault();

    const newNote = {
      id: Date.now() + Math.random(),
      text: "this is a new note",
      status: false
    };
    const appendedList = [...notesList, newNote];

    setNotesList(appendedList);
    localStorage.setItem("ayo", JSON.stringify(appendedList));
  }

  return (
    <>
      <h1>Hello</h1>
      {notesList.map((note) => {
        return <h1 key={note.id}>{note.text}</h1>;
      })}
      <form onSubmit={addNote}>
        <button type="submit">Add Note</button>
      </form>
    </>
  );
}

export default App;
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda