Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 547
marimaf Avatar asked Apr 14 '16 00:04

marimaf


People also ask

How do you fix undefined property Cannot be read?

The “cannot read property of undefined” error occurs when you attempt to access a property or method of a variable that is undefined . You can fix it by adding an undefined check on the variable before accessing it.

Can not read the property then of undefined?

Undefined means that a variable has been declared but has not been assigned a value. In JavaScript, properties and functions can only belong to objects. Since undefined is not an object type, calling a function or a property on such a variable causes the TypeError: Cannot read property of undefined .


1 Answers

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)

like image 66
OJay Avatar answered Sep 18 '22 23:09

OJay