ArtX
ArtX

Reputation: 3

How can I wait until request to Firebase completes and then render app in ReactJS?

My ReactJS app get Firebase database asynchronously, but I want to load a database first and then render app with database. How can I wait or re-render app when database loads?

import React from 'react';
import * as firebase from "firebase/app";
import {config} from './dbinit'
import "firebase/database";

import Home from './panels/Home';

class App extends React.Component {
    constructor(props) {
        super(props);
        this.setState = this.setState.bind(this);
        this.state = {
            activePanel: 'home',

            db: null,
            loading: true,


        };
        console.log("init");
    }

    componentDidMount = () => {
        var self = this;
        let ref = firebase
         .initializeApp(config)
         .database()
         .ref();

        ref.once("value").then(res => {
                        // Async request to Firebase
            console.log("success", res.val())
            if (res.val() != undefined){
                                        // If response not undefined then load it to 'state'
                    this.setState({db: res.val(), loading: false})

            }
        });
        console.log("after")
    }

    go = (e) => {
        this.setState({ activePanel: e.currentTarget.dataset.to })
    };
    render() {
        const { loading, db } = this.state;
        return loading ? (
            <div>loading...</div>
        ) : (
            <View activePanel={this.state.activePanel}>
                <Home id="home" fetchedUser={this.state.fetchedUser} go={this.go} db = {this.db}/>
            </View>

        );
    }
}

export default App;

In render() in 'Home' I pass 'this.db' and trying to get it on 'Home' but there it's undefined.

Upvotes: 0

Views: 493

Answers (1)

Chris Sandvik
Chris Sandvik

Reputation: 1927

In your line for rendering your table, you don't need this.db just simply db

<Home id="home" fetchedUser={this.state.fetchedUser} go={this.go} db = {this.db}/>

should just be

<Home id="home" fetchedUser={this.state.fetchedUser} go={this.go} db = {db}/>

Upvotes: 1

Related Questions