Search code examples
javascriptsweetalert2

sweetalert2: How to have loader animation while redirecting


Using sweetalert2@8 for modal dialogs.

Target is to redirect to a URL when user clicks OK in the dialog. Then while the redirect takes place the sweet_alert must remain open as long as possible, while it shows the loading animation.

Tried the following:

swal.fire({
  title: "my title",
  type: "warning",
  html: "my body text",
  showCancelButton: true,
  showLoaderOnConfirm: true,
  closeOnConfirm: false,
}).then((result) => {
  if(result.value)
  {
      window.location.href = "/target_location/"
  }
})

Results: The redirect works, but the dialog disappears immediately when the OK button is pressed.

How can we keep it visible and show the loader animation?


Solution

  • Two parameters will help with this case: showLoaderOnConfirm and preConfirm.

    From official docs:

    showLoaderOnConfirm

    Set to true to disable buttons and show that something is loading. Use it in combination with the preConfirm parameter.

    preConfirm

    Function to execute before confirm, may be async (Promise-returning) or sync

    Since you want the "infinite" loader which will never stop (browser reload will update the page), you need to return the never-resolving promise in preConfirm():

    Swal.fire({
      showLoaderOnConfirm: true,
      preConfirm: function (value) {
        location.assign('https://google.com')
        return new Promise( resolve => {} ) // never-resolving promise
      },
    })
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@10"></script>