Reputation: 255
I am fetching data from my firebase database in componentDidMount method.
componentDidMount = () => {
firebase.database().ref('posts').on('value', (snapshot) => {
this.setState({
posts: snapshot.val()
})
})
}
I want use this data in my render method. The problem is - when the render method executes, my state is not updated yet, because its async and the state is null. How can I render my data after state changes and i will have my data in my state ?
Upvotes: 2
Views: 65
Reputation: 2317
Before data is retrieved posts field in state is null. Then posts is set and render is called again. You can do something like this:
render(){
if (!this.state.posts){
return <div>Loading</div>;
}
return <div>Render your posts here...</div>
}
Upvotes: 3