Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating the react component state when a global variable changes

I have a global variable that will change often. Let's say it is stored in window.something. In react I need this change to be reflected in the component as well as in its state.

Example code:

class Example extends React.Component {

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


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

However the value gets set only for the first time and there is no change as the variable gets updated.

like image 210
sjishan Avatar asked Mar 28 '18 05:03

sjishan


People also ask

What happens when state variable is changed in React?

This is a function available to all React components that use state, and allows us to let React know that the component state has changed. This way the component knows it should re-render, because its state has changed and its UI will most likely also change. Using a setter function like this is very performant.

How do you update global variables in React?

One way to declare a global variable in React is to attach a new variable as the property of the window object. For example, create a window.name variable in the index. js file like this: import React from "react"; import ReactDOM from "react-dom"; import App from "./App"; window.name = "John"; const root = ReactDOM.

Can we update state directly in React?

React will then look at the virtual DOM, it also has a copy of the old virtual DOM, that is why we shouldn't update the state directly, so we can have two different object references in memory, we have the old virtual DOM as well as the new virtual DOM.


1 Answers

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.

like image 64
Jay Jordan Avatar answered Oct 23 '22 03:10

Jay Jordan