John
John

Reputation: 339

How to force Firebase database call to be synchronous?

I am using firebase with reactjs and i have an issue for rendering data fetched from firebase.

My reactjs component loads before data, so when my webpage is loaded, it remains blank for a short time before data are displayed.

But i don't want my page to load without data have been successfully loaded before. So , i've tried to manipulate state in the constructor but i think the issue come from firebase. Because firebase fetch data asynchronously even in constructor() and componentDidMount()

so render() is called even if firebase didn't finish to send data.

How can i totally prevent react to render without firebase didn't send the result ?

      
      
constructor(props){
super(props)
post = database.ref().child('posts').orderByKey().equalTo(id)
      post.once('value').then(snap => {
        // I get the snap here but i don't want my page to render before 
        // all data queried have been fetched
        
      }).then(function(){
        // I've tried to add a "then" callback but it doesn't work
        // Render is still displayed too soon
      })
      

}

render(){
 let data = this.state.data
 return(
 // simple example
   <span>{this.state.data}</span>
 )
 
}

thanks.

Upvotes: 0

Views: 670

Answers (1)

Brigand
Brigand

Reputation: 86220

You can fetch the data, and then once you have it, and only once you have it, do you ReactDOM.render.

It doesn't stop the page from loading and your css will apply, there just won't be any content in body.

Upvotes: 1

Related Questions