Damiisdandy
Damiisdandy

Reputation: 397

Axios cancelToken, make cancelled request fail silently

I am creating an input form that verifies an account number onChange, using react-hook-form

 useEffect(() => {
    if (account_number.length >= 6) {
      verifyAccountNumber();
    }
    return () => source.cancel('Request canceled!');
  }, [account_number, bank_code, verifyAccountNumber]);

the verifyAccountNumber function runs when account_number and bank_code state changes.

Here is the actual function

const verifyAccountNumber = useCallback(async () => {
    setAccountLoading(true);
    setAccountError({ status: false, serverError: false });
    try {
      const account = await restAPI.get(
        `/misc/verify-account/${account_number}/${bank_code}`,
        { cancelToken: token }
      );
      setAccount(account.data.data.data.account_name);
    } catch (err) {
      console.log(err);
      if (!axios.isCancel(err)) {
        setAccountError({
          status: true,
          serverError: err.response.data.serverError,
        });
      }
    }
    setAccountLoading(false);
  }, [account_number, bank_code]);

is there a way of preventing the try catch block from catching a cancelled request as an error? because its messing up my UI/UX

Upvotes: 0

Views: 1286

Answers (1)

Josef Wittmann
Josef Wittmann

Reputation: 1339

If you want to prevent catching cancellation errors, you have to rethrow it in your case.

if (axios.isCancel(err)) { 
    throw err 
} else { 
    setAccountError(...) 
} 

(Answer from comments to document this issue as resolved)

Upvotes: 1

Related Questions