Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Asynchronous Alerts and Promises | Styling and Advanced Capabilities
Interactive Alerts in React with SweetAlert2

bookAsynchronous Alerts and Promises

SweetAlert2 dialogs are designed to be asynchronous, returning a Promise that resolves when the user interacts with the dialog. When you trigger a SweetAlert2 alert in a React event handler, the function call immediately returns a Promise. This Promise resolves with an object describing how the user dismissed the alertβ€”such as clicking "Confirm" or "Cancel." By leveraging this Promise, you can chain additional logic or asynchronous operations after the user makes a choice, making your UI more dynamic and responsive.

In React, you typically use SweetAlert2 within event handlers like onClick. After displaying an alert, you can use .then() to handle the user's response, and even perform further asynchronous tasksβ€”such as making API calls or updating stateβ€”based on the user's action. This pattern keeps your code clean and ensures that actions only occur after the user confirms or cancels.

Suppose you want to confirm a destructive action, like deleting a user, and only proceed with the deletion if the user clicks "Confirm." You can use SweetAlert2's Promise-based API within your React handler. Here's how you might implement this pattern:

import Swal from 'sweetalert2';

function handleDeleteUser(userId) {
  Swal.fire({
    title: "Are you sure?",
    text: "This action will permanently delete the user.",
    icon: "warning",
    showCancelButton: true,
    confirmButtonText: "Yes, delete it!",
    cancelButtonText: "Cancel"
  }).then(async (result) => {
    if (result.isConfirmed) {
      // Perform the async delete operation
      await deleteUserFromServer(userId);
      Swal.fire("Deleted!", "The user has been deleted.", "success");
    } else if (result.isDismissed) {
      Swal.fire("Cancelled", "The user was not deleted.", "info");
    }
  });
}

// Example async function for deleting a user
async function deleteUserFromServer(userId) {
  // Simulate API call delay
  return new Promise((resolve) => setTimeout(resolve, 1000));
}

In this example, when handleDeleteUser is called (for example, from a button click), the SweetAlert2 dialog appears. If the user confirms, the code waits for the async deletion to finish before showing a success alert. If the user cancels, a different alert is shown. This approach uses Promises to synchronize user interaction with asynchronous logic, ensuring actions only proceed with user consent.

question mark

Which statement best describes how SweetAlert2 Promises are used in a React event handler?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 3. ChapterΒ 3

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

Suggested prompts:

Can you explain how to handle errors if the delete operation fails?

How can I customize the SweetAlert2 dialog further in this example?

What happens if the user closes the dialog without clicking Confirm or Cancel?

bookAsynchronous Alerts and Promises

Swipe to show menu

SweetAlert2 dialogs are designed to be asynchronous, returning a Promise that resolves when the user interacts with the dialog. When you trigger a SweetAlert2 alert in a React event handler, the function call immediately returns a Promise. This Promise resolves with an object describing how the user dismissed the alertβ€”such as clicking "Confirm" or "Cancel." By leveraging this Promise, you can chain additional logic or asynchronous operations after the user makes a choice, making your UI more dynamic and responsive.

In React, you typically use SweetAlert2 within event handlers like onClick. After displaying an alert, you can use .then() to handle the user's response, and even perform further asynchronous tasksβ€”such as making API calls or updating stateβ€”based on the user's action. This pattern keeps your code clean and ensures that actions only occur after the user confirms or cancels.

Suppose you want to confirm a destructive action, like deleting a user, and only proceed with the deletion if the user clicks "Confirm." You can use SweetAlert2's Promise-based API within your React handler. Here's how you might implement this pattern:

import Swal from 'sweetalert2';

function handleDeleteUser(userId) {
  Swal.fire({
    title: "Are you sure?",
    text: "This action will permanently delete the user.",
    icon: "warning",
    showCancelButton: true,
    confirmButtonText: "Yes, delete it!",
    cancelButtonText: "Cancel"
  }).then(async (result) => {
    if (result.isConfirmed) {
      // Perform the async delete operation
      await deleteUserFromServer(userId);
      Swal.fire("Deleted!", "The user has been deleted.", "success");
    } else if (result.isDismissed) {
      Swal.fire("Cancelled", "The user was not deleted.", "info");
    }
  });
}

// Example async function for deleting a user
async function deleteUserFromServer(userId) {
  // Simulate API call delay
  return new Promise((resolve) => setTimeout(resolve, 1000));
}

In this example, when handleDeleteUser is called (for example, from a button click), the SweetAlert2 dialog appears. If the user confirms, the code waits for the async deletion to finish before showing a success alert. If the user cancels, a different alert is shown. This approach uses Promises to synchronize user interaction with asynchronous logic, ensuring actions only proceed with user consent.

question mark

Which statement best describes how SweetAlert2 Promises are used in a React event handler?

Select the correct answer

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 3. ChapterΒ 3
some-alt