I am building a react cryptocurrency project and trying to find out why the loader does not show up at while waiting for an api response. So I have an onClick function that calls an api.
const handleShowSecondScreen = () => {
executeTransaction(price)
.then((res) => {
setIsLoading(true);
if (!res.status) {
setIsLoading(true);
} else if (res.status === 'OK') {
setIsLoading(false);
setSuccessfulTransactionInfo(res);
} else if (res.status === 'FAILED') {
setIsLoading(false);
setWidgetView(SCREEN_VIEWS.FAILED);
}
});
};
So what is supposed to happen is that once I click on the button, the loader is supposed to show up, until after there is a response from the api. However, when I click the button, no loader shows up, and it waits for the response. Not sure what is happening here. Let me know if I am doing something wrong here. Thanks!
CodePudding user response:
You should set the loader before the method call.
const handleShowSecondScreen = () => {
setIsLoading(true);
executeTransaction(price)
.then((res) => {
if (!res.status) {
setIsLoading(true);
} else if (res.status === 'OK') {
setIsLoading(false);
setSuccessfulTransactionInfo(res);
} else if (res.status === 'FAILED') {
setIsLoading(false);
setWidgetView(SCREEN_VIEWS.FAILED);
}
});
};
In your case, you could refactor the code into something like this.
const handleShowSecondScreen = () => {
setIsLoading(true);
executeTransaction(price)
.then((res) => {
if (!res.status) {
return
}
setIsLoading(false);
if (res.status === 'OK') {
setSuccessfulTransactionInfo(res);
} else if (res.status === 'FAILED') {
setWidgetView(SCREEN_VIEWS.FAILED);
}
});
};