Reputation: 1208
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
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
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
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
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