2

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 ?

1

1 Answer 1

3

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>
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.