The Walrus
The Walrus

Reputation: 1208

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

Upvotes: 5

Views: 3443

Answers (4)

Angel
Angel

Reputation: 1788

With the callBack function on the setState API you will fix your problem. In the link is the documentation of setState so you can see the setState and the arguments it accept.

I don't think you need a Async of Promise at this point as you see the onAuthStateChanged return a function, not a promise

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

Upvotes: 0

Ben Hart
Ben Hart

Reputation: 167

you shouldn't make a react lifecycle method async.

do an async await method externally as a helper function then import it:

in a helper file:

async asynchronousFn() {
    const result = await (your asynchronous code)
    return result
}

in the component:

componentDidMount() {
    asynchronousfn().then(result => this.setState({ statekey: result }));
}

Upvotes: 0

João Cunha
João Cunha

Reputation: 10307

I understand the confusion but that line uses callbacks and not Promises so you're not supposed to use async/await

it should be:

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

You can use async/await to replace promises then and catch calls

This

promise.then((result) => {...}).catch((error) => {});

would become

try {
  const result = await promise();
} catch (error) {
  // do stuff
}

Upvotes: 2

messerbill
messerbill

Reputation: 5629

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

Upvotes: 4

Related Questions