Reputation: 171
I am working on an application that needs to fetch some data asynchronously and save the state in the parent component but also pass the data reference to children. The problem is that once the data is loaded in the state, the props do not get updated to the new state. How can I make it so that the props get automatically updated when the parent state changes?
Here's my code:
class App extends Component {
state = {
contract: null,
ethereum: null,
user: null
};
componentDidMount() {
let ethereum = window.ethereum || null;
this.setState({ ethereum });
}
getContainerClasses() {
let classes = "container";
classes += this.state.ethereum === null ? " invisible" : "";
return classes;
}
render() {
return (
<React.Fragment>
<Nav />
<div className={this.getContainerClasses()}>
<Intro ethereum={this.state.ethereum} />
<Load />
<Deploy />
</div>
</React.Fragment>
);
}
}
class Intro extends Component {
constructor() {
super();
this.handleClick = this.handleClick.bind(this);
}
render() {
return (
<React.Fragment>
...
</React.Fragment>
);
}
handleClick() {
console.log(this.props.ethereum);
}
getContainerClasses() {
let classes = "container";
classes += this.props.ethereum !== null ? " " : "";
return classes;
}
}
As you can see in my example I am trying to log this.props.ethereum
on a button click. Unfortunately it doesn't log out the data that is accessible in the App
component (visible in the Chrome React Tools).
Edit:
I misread my logs. The props are updating but the getContainerClasses()
doesn't get fired when the state changes.
Basically what I am trying to do is to hide content while the data is not loaded yet and reveal it as soon as it is.
Upvotes: 0
Views: 160
Reputation: 6674
Probably the moment your component mounts windows.ethereum
hasn't been defined yet. It seems that ethereum
is set in asyn way so your React component doesn't know when it happens. You'd have to add some event listener to react when ethereum
is defined. You can see correct value in dev tools because there you have access to object reference so you always see up-to-date value in dev tools.
Probably you use some ethereum
lib which should include some API method allowing to react on moment when everything is ready and initialized. Below is psedu-code showing how you could achieve it:
componentDidMount() {
ethereum.addEventListener('ready', (ethereumObject) => this.setState({ethereum: ethereumObject}))
}
Upvotes: 1