score:1

Accepted answer

This won't be triggered by a change to a storage object. If you have access to the process that triggered the change, then have it call an update to state. If you don't have access, maybe you could poll for the change every so often.

Personally, I just get it from storage on pages that I need it, or add it to state and use that for the rest of the session.

componentWillMount = () => {
    const foo = JSON.parse(sessionStorage.getItem('foo'));
    const bar = JSON.parse(sessionStorage.getItem('bar'));

    if (!isEmpty(foo) && !isEmpty(bar)) {
        this.props.setFoo(foo);
        this.props.setBar(bar);
    } 
}

Here is a link explaining how to set an event listener on a browser's localStorage.

score:-1

Something like this?

window.something='1234';

  class Example extends React.Component {

    constructor(props) {
      super(props);
      this.state = { something: window.something}
    }

    render() {
      return (
        <div>
          <input defaultValue={window.something}
                 value={this.state.something}
                 onChange={event => {this.setState({'something': event.target.value})}}
          />
        </div>
      )
    }
  }

score:-1

There are 2 approaches in your case:

  1. Whenever the global variable change, re-render the Example component. This is a costly operation.
  2. Example component should listen for a change in window.something. For that there should be some magic which updates your Example component state when window.something changes. Then the component gets updated smoothly.

I suggest second method and use a store system like Redux to implement that magic.


Related Query

More Query from same tag