How to listen sessionStorage in react js?

Viewed 1759

I want to listen to every change inside SessionStorage. Is there a way to listen to it whenever it has changed? I'm using react classes.

class Module extends React.Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
    this.state = {
      ....
    };
  }


  handleClick(e) {
    const value = e.currentTarget.textContent;
    sessionStorage.setItem("AnyValue", value);
  }

  render() {
    return (
      <div
        onClick={this.handleClick}
      >
        {this.props.id}
      </div>
    );
  }
}
1 Answers

You could do

componentDidMount() {
  window.addEventListener('storage', () => {
    console.log("CHANGED!!!");    
  });
}

remember to unmount the listener

componentWillUnmount() {
  window.removeEventListener('storage');
}
Related