Search code examples
javascriptlaravel-livewiresweetalert

Add loading to sweetalert when send request to livewire


I wrote my code below and it works correctly and the answer is received correctly. But the problem is that when the confirm button is clicked, the sweetalert closes

I want the sweetalert not to be closed until the request is fully executed and the loading button to be displayed. I saw a lot of questions about this but they were related to ajax and I could not create them for livewire

document.addEventListener('DOMContentLoaded', function () {
    $('.eg-swal-av3').on("click", function (e) {
        Swal.fire({
            title: 'title',
            text: "content",
            icon: 'info',
            showCancelButton: true,
            confirmButtonText: 'بله ایجاد کن',
            cancelButtonText : 'لغو',
        }).then(function (result) {
            if (result.value) {
                @this.call('createRequest');
            }
        });
        e.preventDefault();
    });
});

Solution

  • You're looking for the preConfirm property, which accepts a callback. This is where you would run the call to your createRequest.

    I would also add a allowOutsideClick to be true when loading, so that the alert is visible throughout the request.

    Swal.fire({
        title: 'title',
        text: "content",
        icon: 'info',
        showCancelButton: true,
        confirmButtonText: 'بله ایجاد کن',
        cancelButtonText : 'لغو',
        allowOutsideClick: () => !Swal.isLoading(),
        preConfirm: function(result) {
            if (result) {
                return @this.call('createRequest').then(() => {
                    Swal.fire('Loading complete');
                });
            }
        },
    });