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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With