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

178
Visualizações
how to get data from localStorage on page reload

I'm trying to make a savable note with React and localStorage. Whenever 'Save' is clicked, it should save the value in the textarea to localStorage, and whenever 'Clear' is clicked, it should clear the textarea and the data from localStorage.

import { useState } from "react";
import "./App.css";

function App() {
  const storage = window.localStorage;
  const [text, setText] = useState('');
  const data = storage.getItem('text');

  return (
    <div className="App">
      <div className="box">
        <div className="field">
          <div className="control">
            <textarea
              className="textarea is-large"
              placeholder="Notes..."
              value={data}
              onChange={(e) => setText(e.target.value)} />
          </div>
        </div>
        <button
          className="button is-large is-primary is-active"
          onClick={() => storage.setItem('text', text)}>Save</button>
        <button
          className="button is-large"
          onClick={() => {storage.removeItem('text'); setText('')}}>Clear</button>
      </div>
    </div>
  );
}

export default App;

It works as supposed, except, when I click 'save', I can't type or delete anything in the textarea. Also, when I click 'clear' it clears the box only after I reload the page.

How can I fix this?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

First, you should set the value of the textarea using the state variable text, otherwise you cannot edit it anymore once you click save. This is because the value on the local storage stays the same when you type, thus making it impossible to update the value.

Second, you need to initialize the state variable text to the value that you have in the local storage if there is any. Otherwise, it will always be empty when you refresh.

The code to apply both of these changes is the following:

function App() {
  const storage = window.localStorage;
  const data = storage.getItem('text');
  const [text, setText] = useState(data ?? '');

  return (
    <div className="App">
      <div className="box">
        <div className="field">
          <div className="control">
            <textarea
              className="textarea is-large"
              placeholder="Notes..."
              value={text}
              onChange={(e) => setText(e.target.value)} />
          </div>
        </div>
        <button
          className="button is-large is-primary is-active"
          onClick={() => storage.setItem('text', text)}>Save</button>
        <button
          className="button is-large"
          onClick={() => {storage.removeItem('text'); setText('')}}>Clear</button>
      </div>
    </div>
  );
}

export default App;
about 4 years ago · Juan Pablo Isaza Relatório

0

In the textArea element you have to assign the "value" as your "text" state.

<textarea
     className="textarea is-large"
     placeholder="Notes..."
     value={text} // --> here
     onChange={(e) => setText(e.target.value)} />

See here: Working example

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