Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store into the local storage ? (REACT)

I have a question for you... On my react app, I have a <input></input> but I would like the user to be able to keep his message thanks to the local storage.

class Profil extends Component {
    message() {
        if (localStorage != 'undefined'){
            document.getElementById('message').value = localStorage.getItem('message');
        }
        else {
            alert("localStorage is not supported");
        }
    }
    render() {
        return (
            <div>
                <input name="message" onChange={() => this.message()}></input>
            </div>
        );
    }}

With that, when I put a letter, I have directly an error message :

TypeError: localStorage.getItem(...) is null

and this line is false :

document.getElementById('message').value = localStorage.getItem('message');

What do I have to do ?

like image 924
From Avatar asked Sep 02 '25 15:09

From


1 Answers

Instead of manipulating the DOM manually, you could keep the message in state and update the localStorage value on every change, and also read the value from localStorage when the component is created.

Example

class Profile extends React.Component {
  constructor() {
    super();
    this.state = {
      message: localStorage.getItem("message") || ""
    };
  }

  onChange = event => {
    const message = event.target.value;

    localStorage.setItem("message", message);
    this.setState({ message });
  };

  render() {
    return <input value={this.state.message} onChange={this.onChange} />;
  }
}
like image 83
Tholle Avatar answered Sep 05 '25 07:09

Tholle