I'm building a website and using exclusively SweetAlert2 for my confirmation methods (notification of success, edition or deletion).
Since it takes quite a lot of lines, I decided to set everything related to SweetAlert in a JS file that i would call and use as a function, as follows:
// src/config/SweetAlert.js
import swal from 'sweetalert2'
import 'sweetalert2/src/sweetalert2.scss'
import axios from 'axios'
const API = axios.create({
baseURL: 'http://localhost:3333/api/v1'
})
const SweetAlert = {
delete (title, text, type, confirmation, url) {
swal({
title: title,
text: text,
type: type,
showCancelButton: true,
showLoaderOnConfirm: true,
confirmButtonText: 'Delete',
preConfirm: () => {
return API.delete(url)
.then(response => {
return response
})
},
allowOutsideClick: () => !swal.isLoading()
}).then((result) => {
if (result.value) {
swal({
type: 'success',
title: confirmation
})
}
})
},
// Some other possibilities
}
export default SweetAlert
And I use it as follows:
// some methods
handleDelete (post, index) {
const result = SweetAlert.delete(
`Delete "${post.title}"?`,
`Are you sure you want to delete "${post.tite}"?`,
'warning',
`"${post.title}" was successfully deleted`,
`/post/${post.id}`
)
}
I would like to make sure everything went well in my API before removing the deleted element from the list. I tried adding return result.value
since there is the following code block:
if (result.value) {
swal({
type: 'success',
title: confirmation
})
// Returns undefined as soon as SweetAlert shows up
return result.value
// shows up only when I click "Delete" on the Swal modal, has the infos I need
}
I tried to change my code to the following:
const result = SweetAlert.delete( // my initial code )
if (result.data === 'ok') {
this.posts.splice(index, 1)
}
But all I get is "undefined".
Is there a way to retrieve this kind of data?
Thank you in advance
Swal returns a Promise, so make use of it in your delete
function like that:
delete (title, text, type, confirmation, url) {
let res = swal({
// your code here ...
});
res.then(result => {
// your code here ...
})
return res;
)
After that you could use it like this:
SweetAlert.delete( // my initial code )
.then(result => {
if (result.value) {
this.posts.splice(index, 1);
}
})
.catch(error => {
console.log('error', error)
})