Async is waiting for the component

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

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

I tried using async / wait but im did not use it 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 wait for lines 2-6 before calling the props function on line 7

+5
source share
4 answers

you need to use the .setState() callback function:

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

Hello

+4
source

I understand the confusion, but this line uses callbacks, not Promises, so you should not 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

it

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

will become

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

you should not respond to the async life cycle.

execute the async await method externally as a helper function, then import it:

in the auxiliary file:

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

in component:

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

With the callBack function in the setState API, you fix your problem. The link has setState documentation so you can see setState and the arguments it takes.

I don’t think you need Async of Promise at this moment as you see onAuthStateChanged return function, not promise

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

Source: https://habr.com/ru/post/1275017/


All Articles