Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async await on component did mount

This is my componentDidMount method. I want to set the state of the current user and then call the function when that user is set. How can I do this?

  componentDidMount = () => {
    firebase.auth().onAuthStateChanged((user) => {
      if (user) {
        this.setState({user: user})
      }
    });
    this.props.retrieveMatches(this.state.user.uid)
  }

I've tried using async/await but im not using it correctly here:

  async componentDidMount = () => {
    await firebase.auth().onAuthStateChanged((user) => {
      if (user) {
        this.setState({user: user})
      }
    });
    this.props.retrieveMatches(this.state.user.uid)
  }

basically I want to await for lines 2-6 before calling the props function on line 7

like image 608
The Walrus Avatar asked Jan 29 '18 14:01

The Walrus


1 Answers

you need to use .setState()'s callback function:

componentDidMount = () => {
  firebase.auth().onAuthStateChanged((user) => {
    if (user) {
      this.setState({user: user}, () => { 
        this.props.retrieveMatches(this.state.user.uid); 
      })
    }
  });
}

greetings

like image 164
messerbill Avatar answered Sep 21 '22 13:09

messerbill