Implementing SweetAlert2 in Vue.js to create a modal prompt for confirmation prior to deleting an item

I'm encountering an issue with sweetalert2 while using Laravel Vue for my app development. My goal is to have a confirmation modal pop-up when deleting a row from the database. However, whenever I click "Yes", the item is successfully removed. But if I click the cancel button, the modal closes and still deletes the entire row. This has left me feeling confused as this is my first time working with these frameworks, and I am eager to learn more about them.

Below is the code snippet from IndexComponent.vue:

methods: {
        deletePost(id) {
            this.$swal({
                title: 'Are you sure?',
                text: "You won't be able to revert this!",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: 'Yes, delete it!',
                closeOnCancel: true
                }).then((result) => {
                    //send request to server 
                    let uri = `/api/post/delete/${id}`;
                    axios.delete(uri).then(response => {
                        this.posts.splice(this.posts.indexOf(id), 1);
                    });
                    if (result.value) {
                        this.$swal(
                        'Deleted!',
                        'Your post has been deleted!',
                        'success'
                        )
                    }
                })
        }
    }

This is the button in my table cell that triggers the deletion functionality:

<td><button @click="deletePost(post.id)" class="btn btn-danger">Delete</button></td>

And here is the excerpt from PostController.php:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Resources\PostCollection;
use App\Post;

public function delete($id) {
    $post=Post::find($id);
    $post->delete();
    return response()->json('Successfully deleted!');
}

All CRUD operations are functioning correctly, but the implementation of sweetalert2 seems to be resulting in multiple deletions. Can anyone offer some assistance on this matter?

Answer №1

It's important to remember to place your API call inside an 'if' statement as shown below:

methods: {
    deletePost(id) {
        this.$swal({
            title: 'Are you sure?',
            text: "You won't be able to revert this!",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#3085d6',
            cancelButtonColor: '#d33',
            confirmButtonText: 'Yes, delete it!',
            closeOnCancel: true
            }).then((result) => {
                //send request to server 
                if (result.value) {
                     let uri = `/api/post/delete/${id}`;
                    axios.delete(uri).then(response => {
                      this.posts.splice(this.posts.indexOf(id), 1);
                    });
                    this.$swal(
                    'Deleted!',
                    'Your post has been deleted!',
                    'success'
                    )
                }
            })
    }
}

Answer №2

The splice method's index is incorrect in your code. Instead of returning the desired index, it will return -1 and delete the last item.

To rectify this issue, the correct approach would be:

this.posts = this.posts.filter(post => post.id !== id)

Complete code snippet:

methods: {
  deletePost(id) {
    this.$swal({
        title: 'Are you sure?',
        text: "You won't be able to revert this!",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: 'Yes, delete it!',
        closeOnCancel: true
        }).then((result) => {
            //send request to server 
            if (result.value) {
              let uri = `/api/post/delete/${id}`;
              axios.delete(uri).then(response => {
                this.posts = this.posts.filter(post => post.id !== id)
                this.$swal(
                  'Deleted!',
                  'Your post has been deleted!',
                  'success'
                )
              });
            }
      })
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Navigating Redirect Uri in Ionic for third-party API integration

After creating a webapp, I decided to venture into developing a mobile app using Ionic. The idea of making a progressive web app crossed my mind, but unfortunately Apple doesn't support it yet. (By the way, I'm still quite new to all of this) F ...

Having trouble with the animate() function not working properly?

I have been working on the following code snippet: var isOn = false; $('.switch').on("click",function(){ if (isOn){ $('.toggle').animate({ left:"18px" },10,"linear", { complete: function(){ $(&ap ...

Add the useState hook from React to an array

Hey there, I need some help with my code. I am trying to add an element to my array, but it's not working as expected. Can you take a look at what I have written below? const [datesState, setDisabledData] = useState([ format(new Date(2021, 4, 1) ...

Encountering an Error while Setting Up NextJS on Vercel

Hello, I'm a newcomer to the world of web development. My current goal is to deploy my first NextJS app on Vercel, but I keep encountering an error. Error: SyntaxError: Unexpected token T in JSON at position 0 at JSON.parse (<anonymous>) ...

Error: A problem occurred that was not caught in the promise, please investigate further

@Injectable() class MyErrorHandler implements ErrorHandler { handleError(error) { // an error occurred in a service class method. console.log('Error in MyErrorhandler - %s', error); if(error == 'Something went wrong'){ ...

There appears to be a JavaScript validation error occurring on the current page, however, you are able

For my datepicker, I want an error message to display if the user selects a date more than 5 years in the future, saying "You are ineligible for our program". The user should not be able to proceed to the next step unless this error message is ad ...

Securing a single component within a named view router in Vue.js

Within my routes configuration, I have a named view route set up: let routes = [ { name: "home", path: '/', components: { default: Home, project: ProjectIndex } } ] The goal is to ...

Using JavaScript to trigger actions via links or buttons inside a table will only function properly in the first row

After multiple consecutive Ajax requests to refill an HTML table, there seems to be a strange issue. The links in the first row of the table are functioning properly and call JavaScript functions, but for any subsequent rows, the links or buttons stop work ...

JavaScript code: Determine if a set of x/y points represents a circular shape

I have a matrix in the format below. I am looking for help to identify the outline that forms a circle: EDIT 1: What about the outline? The outline should not include spaces (each y-value should have at least 2 x-values). EDIT 2: What is considered a cir ...

Retrieving display format or formatted value from an object with Moment.js

I am currently working on a project using Angular and Material2. Within this project, I have created a moment object in the following way: myDate = moment.utc(new Date()).format("YYYY-MM-DD HH:mm:ss"); This object is then passed as an argument to ano ...

Troubleshooting: Node.js Express Server GET Handler Failing to Function

Recently, I've been attempting to build a GET request handler in Express.js. Here's the snippet of code I've put together: // include necessary files and packages const express = require('./data.json'); var app = express(); var m ...

Using PHP's $_GET with an Ajax/Jquery Request

I've been struggling to set a variable $id=$_GET["categoryID"] and can't seem to make it work. I suspect it's related to the Ajax request, but I'm unsure how to format it correctly to work with the request for my mysql query. Any assist ...

Nuxt router directing to incorrect URL upon refreshing the page

Let me show you exactly what I mean by setting up a demo Nuxt blog at https://example.com/nuxtblog/. This demonstration includes articles populated by the @nuxt/content package. The website has been generated statically using the nuxt generate command. Fol ...

Alternative to updating object coordinates in Fabric JS 1.7.9 - seeking solutions for migration challenges

Update: JSFiddle: https://jsfiddle.net/Qanary/915fg6ka/ I am currently working on implementing the `curveText` function (found at the bottom of this post). It was functioning properly with `fabric.js 1.2.0`, but after updating to `fabric.js 1.7.9`, I not ...

Learning how to utilize localStorage in conjunction with a color picker to modify the --var of :root

After spending an entire afternoon on my JavaScript issue as a beginner, I have a specific goal in mind: allowing the user to select and change the main color of the page. To implement this, I inserted a color picker in my HTML: <input type="color ...

Discover how to access all of the response headers from an HTTP request in Angular

Currently, I am utilizing HttpClient to make a request for a `json` file. My intention is to have the file cached using `ETag`, however, this feature does not seem to be functioning as expected. Upon investigation, it appears that the absence of sending of ...

A method to find the sum of the final n elements in an array by employing Arr.reduceRight

I have successfully calculated the sum of the last n elements in an array using a for loop. Is it possible to achieve the same result using Arr.reduceRight instead? x = [1,2,3,4,5]; y = 0 for(let i=x.length; i>x.length-3; i--) { console.log(x[i-1]); ...

How can I define the boundaries for the scrolling of a static background image?

Is there a way to limit how far a fixed background image can scroll down a page? Essentially, is it possible to change the background attachment to static when the bottom of the background image is 10px away from the bottom edge of its div container? In t ...

VueJS - Input Image Display Issue Causing Browser Slowdown

I'm experiencing some issues with my VueJS component that includes a file input and displays an image afterwards. Strangely, this is causing my web browsers (both Firefox and Chromium) to freeze up and use massive amounts of CPU. I tried switching to ...

There seems to be an issue with the hidden field value not being properly set within the

I created a function called getConvertionValue. Inside this function, I make an ajax call to the getCurrencyConvertion function in the controller. function getConvertionValue(from, to) { if (from != to) { $.ajax({ url: base_url + 'admin/o ...