Suppose that I have a Modal inside a Component and I want to show the Modal when some buttons are clicked:
render(){
...
<Modal
is={this.state.productId}
visilble={this.state.visible}
/>
}
Inside the Modal Component, I want to call API to get the product detail based on the selected id as the following:
componentWillReceiveProps(nextProps) {
if(nextProps.visible && !this.props.visible) {
fetch(...).then(res => {
this.setState({
product: res.data
})
}).catch(err => {
...
})
}
}
From the React docs it says that componentWillReceiveProps, componentWillUpdate is deprecated and you should avoid them in new code.So I try use static getDerivedStateFromProps()
static getDerivedStateFromProps()(nextProps) {
if(nextProps.visible && ...) {
fetch(...).then(res => {
return {
product: res.data
}
}).catch(err => {
...
})
} else return null (or just return null here without else)
}
The above code doesn't work since fetch is asynchronous so it always returns null or doesn't return anything, you can't use await here to wait for the api to resolve also, and I heard that getDerivedStateFromProps shouldn't use for data fetching.
So what is the best way solve the problem ?
I think it's better to decide whether to show Modal component or not in parent component as Modal component should be a functional component to render only modal related view. This way every time Modal component will not be rendered and only rendered when visible flag is true.
{ this.state.visible &&
<Modal />
}
In parent component you could fetch data in componentDidMount if just after initial render the data is required or componentDidUpdate if after every update the fetch data is required for modal. After fetching data set state of visible to true.
Happy Coding!!!
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