skip to Main Content

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?

2

Answers


  1. 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:
    output Image
    Note:
    This Wont Work if you are running javascript separately.

    Login or Signup to reply.
  2. 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();
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search