Home > Enterprise >  How do I detect if axios request is in loading phase while using async/await?
How do I detect if axios request is in loading phase while using async/await?

Time:11-18

I need to detect if the axios request (with async/await) is in loading phase. 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.

CodePudding user response:

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
}

CodePudding user response:

You can achieve this behavior by using the following steps:

1 - Create a state called isLoading and initialize it to false.

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

2 - Get the current state of data fetching:

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:

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

This is a sample demo in codesandbox.

  • Related