Uncaught TypeError: Cannot read property 'then' of undefined using Sweet Alert

marimaf picture marimaf · Apr 14, 2016 · Viewed 15.7k times · Source

I am using SweetAlert2 and I am getting the following error

Uncaught TypeError: Cannot read property 'then' of undefined

When I use the exact same code as suggested in SweetAlert page.

swal({
title: 'Are you sure?',
  text: "You won't be able to revert this!",
  type: 'warning',
  showCancelButton: true,
  confirmButtonColor: '#3085d6',
  cancelButtonColor: '#d33',
  confirmButtonText: 'Yes, delete it!',
  cancelButtonText: 'No, cancel!',
  confirmButtonClass: 'btn btn-success',
  cancelButtonClass: 'btn btn-danger',
  buttonsStyling: false,
  closeOnConfirm: false,
  closeOnCancel: false
}).then(function(isConfirm) {
  if (isConfirm === true) {
    swal(
      'Deleted!',
      'Your file has been deleted.',
      'success'
    );
  } else if (isConfirm === false) {
    swal(
      'Cancelled',
      'Your imaginary file is safe :)',
      'error'
    );
  } else {
    // Esc, close button or outside click
    // isConfirm is undefined
  }
})

I have the code at the end of the page. I am using it in a Ruby on Rails app. I have tried returning a value as suggested in other posts, but it does not fix the problem

Answer

OJay picture OJay · Apr 14, 2016

looks as thought the sweetalert2 implementation uses the native promise api, and there is no included polyfill. Meaning might not work in some browsers. Even the github page shows the same error. Works fine when I try it in chrome, but does not work in IE11. I would look at including a promise API polyfill, depending on what browser/s you are trying to support. This has nothing to do with rails.

Polyfill is here or google ES6 promise polyfill. Include it before the sweetalert2 js file and you should be fine.

If don't understand what I am talking about with the promise API, good article here about it, or google JS promise.

Now if all of this is too hard, and/or confusing, why not just use the original sweetalert (link here) as it doesn't use the promise api. Not exactly sure why they forked, as I can't see any drastically new functionality, apart from using promises of course, and a couple of new modal icons (info and question)