'Good practice handling Axios errors in React
I have a doubt about handling API call errors using Axios. This is working for me but it seems I am using too much logic inside the Catch error Callback.
const onSubmit = async (data) => {
await axios
.post("http://localhost:3001/auth/verify-email", data, {
headers: {
"Content-Type": "application/json",
},
})
.then((res) =>
navigate("/", {
state: {
response: res.data.result,
verified: true,
message: "You have succesfully registered",
},
})
)
.catch((error) => {
if (error.response.data.errors[0].code === "InvalidToken") {
axios.get(`http://localhost:5001/auth/verify-email/${data.email}`);
alert("Check your email for the new Verification Code");
navigate("/authentication", {
state: { email: data.email },
});
}
});
};
In this case if one sort of error happens, then it calls an API to reset the token. It works fine but maybe it can be refactored.
Solution 1:[1]
Check axios doc on errors
If you want to extract the error code in a "cleaner" way, you can treat it this way : error.toJSON()
This way your logic to catch the error will be less "messy"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | garlic-lover |
