So I currently have this code that asks the user if they want to delete a record from the database via ReactJS
methods: {
async deleteStatus(id) {
try {
if (window.confirm("Do you really want to delete?")){
await axios.delete(`http://localhost:5000/delete-status/${id}`);
}
window.location.reload();
} catch (err) {
console.log(err);
}
},
},
Now my goal is to create an error message saying "Cannot Delete" If the record cannot be deleted, mainly due to a foreign key constraint in the backend. Is there a window function or a button function that relay that information to the user?
CodePudding user response:
If You are using Javascript in HTML page or a local HTML server.
Then,
In The Catch,
You Have To Write alert("Cannot Delete");
This Will Look Like:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<script>
try {
//Your Code Here
} catch (error) {
alert("Cannot Delete");
//OR
alert(error);
}
</script>
</body>
</html>
And Output Will Be:
Note:
This Wont Work if you are running javascript separately.
CodePudding user response:
You can simply do that by getting the response from your delete API and based on that you can do that in the try
block.
If there will be any error while deleting the record, API will return some different status code or message based on that you can do this.
try {
if (window.confirm("Do you really want to delete?")){
const res = await axios.delete(`http://localhost:5000/delete-status/${id}`);
if (res.message === 'Success') {
alert('Successfully Deleted');
} else {
alert('Cannot Delete');
}
}
window.location.reload();
}