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?