AHR
AHR

Reputation: 147

Get Firestore data before rendering in React

I'm trying to create a basic profile page which runs a get request on a Firestore DB containing users, then returns the found user's info. As of now, my webpage never loads, likely because the render method is called before my get request completes. I can verify my get request is working correctly through console.log statements. What can I do to ensure the page updates once the user has been retrieved from the DB? Thanks!

class Profile extends Component{

  constructor (props) {
    super(props);
    this.state = {
      uid: 'sampleID',
      user: null,
      isLoaded: false
    };
  }

  componentDidMount () {
    firestore.collection('user').doc(this.state.uid).get()
    .then(res => { 
      this.setState({
        user: res.data(),
        isLoaded: true
        })
      }
    );
  }

    render() {
      return (
        <div>
          {this.state.isLoading ? <h3> Welcome {this.state.user.displayName} </h3> : <h3> Loading </h3>}
        </div>
      );
    } 
  }

Upvotes: 0

Views: 200

Answers (1)

Jason Parra
Jason Parra

Reputation: 97

It will not load because "this.state.isLoading" is undefined, it should be "this.state.isLoaded"

render() {
  return (
    <div>
      {this.state.isLoaded? <h3> Welcome {this.state.user.displayName} </h3> : <h3> Loading </h3>}
    </div>
  );
} 

When the request completes it would make the setState and call the render again, your data will be displayed.

Upvotes: 1

Related Questions