Reputation: 404
I have a scenario wherein if I save a duplicate record in DB, the modal should show the exact error message
POST request using axios:
saveBankMaintenance(optionsBrstn){
return axios.post(`${API_URL_SAVE_BANK_MAINTENANCE}`,
[optionsBrstn]
)
I'm calling this POST request using:
const saveBrstn = useCallback(() => {
ClientMaintenanceService.saveBankMaintenance(optionsBrstn)
.then((response) => {
if(response.data.success === "Success"){
setShowBrstnSaveSuccessModal(true);
setShowBrstnSaveFailedModal(false);
}
}).catch((err) => {
setShowBrstnSaveSuccessModal(false);
setShowBrstnSaveFailedModal(true);
})
});
Saving is OK if its successful
However, when it fails, it goes straight to the catch
block and I can't set the error message on the state
Is there a way for me to get the json response (containing the error message) alongside the http status response 400?
TIA
Upvotes: 5
Views: 11111
Reputation: 10569
You could get the response data in error
object in the response
property.
Try this.
const saveBrstn = useCallback(() => {
ClientMaintenanceService.saveBankMaintenance(optionsBrstn)
.then((response) => {
if (response.data.success === "Success") {
setShowBrstnSaveSuccessModal(true);
setShowBrstnSaveFailedModal(false);
}
}).catch((err) => {
console.log(err.response.data); // you can get the response like this
console.log(err.response.status); // status code of the request
})
});
Upvotes: 13