Intensify the loading dialog with SweetAlert2
Recently, I required a modal to inform the user that a significant operation is in progress. After the XHR request is completed, display a success message.
You can use Swal2 to show a loading dialog and then hide it after an asynchronous operation, such as fetching data. Here's a basic example using Vue 3, TypeScript, and SweetAlert2:
// Import SweetAlert2
import Swal from 'sweetalert2';
export default {
methods: {
async fetchData() {
// Show loading dialog
Swal.fire({
icon: 'info',
title: 'Momentje geduld...',
allowEscapeKey: false,
allowOutsideClick: false,
showConfirmButton: false,
willOpen: () => {
Swal.showLoading(null);
},
});
try {
// Simulate fetching data (replace this with your actual fetch)
await this.simulateFetch();
// Hide loading dialog
Swal.close();
} catch (error) {
// Handle errors if needed
console.error('Error fetching data:', error);
// Hide loading dialog in case of an error
Swal.close();
}
},
// Simulate fetching data
simulateFetch() {
return new Promise((resolve) => {
setTimeout(() => {
resolve();
}, 2000); // Simulating a 2-second fetch delay
});
},
},
};
In this example, the fetchData
method shows a loading dialog using SweetAlert2, then simulates fetching data with the simulateFetch
method. After the data is fetched (or if there's an error), the loading dialog is closed. Adjust the simulateFetch
function with your actual data-fetching logic.
Et voila.