Reputation: 45
I have a react app and I would like to fetch some data asynchronously, process it, change the current components state, and then pass it as props to another component in the render. I tried fetching it in componentWillMount, but seems like the render still happens before data is fetched. What is a working solution for that? I also tried fetching the data in a ES6 contructor, and the issue still persists.
Any help is greatly appreciated!
Upvotes: 3
Views: 1215
Reputation: 281676
Well an ideal place to fetch the data would be the componentWillMount
function, however because of the async nature your child component may get rendered before the data is fetched and hence you can do two things.
Maintain a loading state that doesn't render the component till the result is fetched, like:
constructor() {
super();
this.state = {
isLoading: true,
// other states
}
}
componentWillMount() {
//your async request here
}
render() {
if(this.state.isLoading) {
return null; // or you can render laoding spinner here
} else {
return (
//JSX here with the props
)
}
}
Other way is to have an empty prop and perform for a check in the child component:
constructor() {
super();
this.state = {
someProps: null;
}
}
componentWillMount() {
//your async request here
}
render() {
return (
<Child someProps={this.state.someProps}/>
)
}
Child
render() {
if(this.props.someProps == null)
return null;
else {
return (//JSX contents here);
}
}
Upvotes: 4