1

I'm doing a feature using react, which saves text from input and automatically updates to local storage, I want even if I refresh the page the text in the input stays and the state doesn't reset from scratch. Thanks for helping me, have a nice day. please give me an the demo in the following codesandbox codesandbox link. one more time thank you very much

Tam Do
  • 181
  • 4
  • 15

1 Answers1

5

First you want to store your input's value in react state

const [value, setValue] = useState("");

When the input changes, write the change to react state, and also localStorage

const handleChange = (e) => {
  setValue(e.target.value);
  localStorage.setItem("inputValue", e.target.value);
};

When the component is mounted, we want to set the initial state of the input to the value in localStorage

useEffect(() => {
  setValue(localStorage.getItem("inputValue"));
}, []);

Finally, hook the handler to onChange, and use the React state as the form value

<input
  value={value}
  onChange={handleChange}
/>

See: https://codesandbox.io/s/react-input-not-reload-after-refreshing-forked-q84r8?file=/demo.js

Thad Blankenship
  • 2,242
  • 3
  • 16
  • 16
  • Thank you so much, it is very straight forward – Tam Do Sep 11 '20 at 16:58
  • 1
    I would suggest that you instantly set value: `useState(localStorage.getItem("inputValue")`. Gives the same result. I guess this is less code, no need for an extra `useEffect` – Mario Petrovic Sep 14 '20 at 14:54
  • No i still use useEffect, when the value of localstorage changed it will update the state instantly, if i remove it, it just render the previous component because it can listen to the change automatically, useState is designed for render the first mounted component – Tam Do Sep 14 '20 at 16:45
  • Thank you so much by the way for help me out Mario – Tam Do Sep 14 '20 at 16:45