Sorry if this is obvious somewhere in the documentation, but I am trying to wait until my state is set on a parent component before rendering a child component:
Paraphrasing:
class Parent extends Component {
componentWillMount() {
firestack.database.ref()
.then((snapshot) => {
this.setState({myVal: snapshot.val})
})
}
render() {
// Renders before request finishes setting state,
// Child component receives an undefined val
return (
<ChildComponent
myVal={this.state.myVal}
/>
)
}
}
My render hits before the request finishes, so I'm not able to pass the new State to the child component's constructor. How can I properly do this? Hopefully this is low hanging fruit to someone.
First, I recommend moving your async request to componentDidMount. Not mandatory, but it's a better point in the life-cycle. Your component will need to able to handle myVal == undefined anyway.
Then, don't render the child component until myVal is available:
render() {
return (
<div>
{ this.state.myVal && <ChildComponent myVal={this.state.myVal} /> }
</div>
)
}
Or perhaps, render a spinner instead:
render() {
return (
<div>
{ this.state.myVal
? <ChildComponent myVal={this.state.myVal} />
: <Spinner />
}
</div>
)
}
Note:
You can't use if inside JSX, so this not-so-kosher use of && is required to keep the syntax compact. A common pattern.
You can have a this.state.isReady boolean instead of asking for the presence of a specific value. Another common pattern.
If ChildComponent is the only element you're going to render, you may not need the <div /> wrapper, but you usually do for some reason or other.
If the myVal parameter is a required for ChildComponent, you just need to do this in parent:
return (
{this.state.myVal !== undefined &&
<ChildComponent
myVal={this.state.myVal}
/>
}
)
Then react will render empty string at first time and after changing state it will render again with filled myVal value.
Also, as it was mentioned in another answer, it's much better to use componentDidMount.
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