简体   繁体   English

使用异步/等待时,如何检测 axios 请求是否处于加载阶段?

[英]How do I detect if axios request is in loading phase while using async/await?

I need to detect if the axios request (with async/await) is in loading phase.我需要检测 axios 请求(使用异步/等待)是否处于加载阶段。 Because, I need to disable a button if the request is loading.因为,如果请求正在加载,我需要禁用一个按钮。

So, this is the line of code:所以,这是一行代码:

const response = await API.get("/url", options);

Now, I need to disable a certain button if this request is in loading phase.现在,如果此请求处于加载阶段,我需要禁用某个按钮。 But, I'm stuck on how to solve this issue.但是,我坚持如何解决这个问题。

setState(true) //to initiate loading
const response = await API.get("/url", options);
setState(false) //to turn off loading
try{
setState(true) //to initiate loading
const response = await API.get("/url", options);
}
catch(err){}
finally{
setState(false) //to turn off loading
}

You can achieve this behavior by using the following steps:您可以使用以下步骤实现此行为:

1 - Create a state called isLoading and initialize it to false . 1 -创建一个名为isLoading并将其初始化为false

const [isloading, setIsloading] = useState(false);

2 - Get the current state of data fetching: 2 -获取当前 state 的数据获取:

const fetchingData = async () => {
    try {
        setIsloading(true); // Set loading before sending API request
        const response = await API.get("/url", options);
        ....
        setIsloading(false); // Stop loading
    } catch (error) {
        setIsloading(false); // Stop loading in case of error
        console.error(error);
    }
}

3 - Disable button conditionally: 3 -有条件地禁用按钮:

<button disabled={isloading ? true : false}> button disabled while fetching data</button>

This is a sample demo in codesandbox .这是codesandbox中的示例演示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM