'Why the item is not saved on the localStorage?

Working on a simple project using react js. What I'm trying to do is to save the "item"(which has an input field for the user to put it) in the localStorage, for the purpose when a user reloads or navigate to other components the item won't be gone, but it will be there.

AddItem.js:

export default class AddItem extends React.Component {

  userItems;

  constructor(props) {
    super(props);

    this.state = {
      content: "",
      items: [],
    };
  }

  update(event) {
    this.setState({
      message: event.target.value,
    });
  }
  componentDidMount() {
    this.userItems = JSON.parse(localStorage.getItem('items'));

    if (localStorage.getItem('items')){
      this.setState({
        items: this.userItems.items,
        message: this.userItems.message
      })
    }else {
      this.setState({
        items: [],
        message: ""
      })
    }
  }

    componentWillUpdate(nextProps, nextState){
    localStorage.setItem('item', JSON.stringify(nextState));
  }


  handleClick() {
    var items = this.state.items;

    items.push(this.state.message);

    this.setState({
      items: items,
      content: "",
    });
  }

  handleChanged(j, event) {
    let items = this.state.items;
    items[j] = event.target.value;

    this.setState({
      items: items,
    });


  }







The problem is that when I type an item in the input field, and I reload the page, the component is not shown at all.

In the application, at the local storage, the value is shown at the google inspect:
enter image description here

But as soon as I navigate to another component or I reload that page, the storage becomes empty like it was in the first time. How can I make it work, so the value doesn't go away when I navigate to another page?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source