I have a function that makes a call to get a new access token getNewAccessToken() and in the method sets the token in state. Then another method postComment() is called but it doesn't have the correct accessToken in state yet (since the setstate was an async call and probably doesn't have the value yet. What is the best way to fix this to ensure postComment() has the correct state value?
goPost() {
console.log("In goPost()");
this.getNewAccessToken();
this.postComment();
}
async getNewAccessToken(){
const response = await fetch(
`https://www.reddit.com/api/v1/access_token`... set up fetch
);
if (response.ok) {
this.setState({
accessToken: json.access_token
});
}
}
async postComment() {
let accessToken = this.state.accessToken;
}
So these are all asynchronous calls, meaning they do not get fired in a predictable order. To make this work, you have to take matters into hand and force the order of execution. In order to do this change, your goPost function should be converted to an async call. Then, it should await the subsequent calls to force a pause to get the token.
async goPost() {
console.log("In goPost()");
await this.getRefreshToken();
this.postComment();
}
So now the this.postComment will not be executed until you receive your token. Also additional note, there is no need to make post comment asynchronous unless you plan to do aync things inside that function.
Asynchronous programming is a tricky subject! It is good if you can read more on these concepts so that you have a solid footing on the way these things work! Watch this to learn more, it helped me a lot!