How to await for the response of Alert dialog in React Native?

react native alert
react-native-dialog
alert onpress in react native
alert cancel react native
alert modal react-native
react native dismiss alert
react native alert with input
react native error message

From my observation, the Alert dialog seems built on top of the React Native app. So it pops out everytime you call it, and doesn't to be in the render function. The catch is it is not an async task so the code after Alert will continue to execute regardless the callback function.

The code below demonstrates a situation where the Alert dialog keeps popping out because it reads the same barcode over and over again. (It is written in TypeScript. Just take my word, this is a valid snippet.)

 import * as React from "react";
 import Camera from "react-native-camera";
 import { Alert } from "react-native";

 export default class BarcodeScanSreen extends React.Component<any ,any> {
 private _camera;
 private _onBarCodeRead = e => {
    if (e.type === "QR_CODE") {
        Alert.alert(
            "QRCode detected",
            "Do you like to run the QRCode?",
            [
                { text: "No", onPress: this._onNoPress },
                { text: "Yes", onPress: this._onYesPress }
            ],
            { cancelable: false }
        );
    }
};

 private _onYesPress = () => { /* process the QRCode */ }

 private _onNoPress = () => { /* close the alert dialog. */ }

render() {
    return (
        <Camera
            onBarCodeRead={this._onBarCodeRead}
            aspect={Camera.constants.Aspect.fill}
            ref={ref => (this._camera = ref)}
        >
            {/* Some another somponents which on top of the camera preview... */}
        </Camera>
    );
}
}

Is there a way to pause the JS code and await the response from Alert?

Alert does not pause the code. In this case JS is not the only problem - the Camera component also keeps running in the background which is native and it will trigger the onBarCodeRead listener, regardless if the Alert is present or not.

You could try to stop the camera at the beginning on _onBarCodeRead with the stopPreview() method mentioned in the docs.

Also note that react-native-camera is currently in a migration process from Camera (RCTCamera) to RNCamera and in the new RNCamera I don't see a stopPreview() method. Anyhow, a simple flag would also do the job.

Can React native Alert wait for user response?, From my observation, the Alert dialog seems built on top of the React Native app. So it pops out everytime you call it, and doesn't to be in the  A modal dialog that interrupts the user's workflow to get a response, usually some sort of confirmation. This is different than a typical Dialog in that it requires some user response, like "Save", or "Cancel", etc. Most of the time you'll use AlertDialog, AlertDialogLabel, and AlertDialogDescription together.

React-native Alert doesn't stop the execution of code below it. By changing it to async function which resolves the promise on user action will work as ASYNC-Alert.

const AsyncAlert = async () => new Promise((resolve) => {
  Alert.alert(
    'info',
    'Message',
    [
      {
        text: 'ok',
        onPress: () => {
          resolve('YES');
        },
      },
    ],
    { cancelable: false },
  );
});

await AsyncAlert();

How to await for the response of Alert dialog in React Native?, From my observation, the Alert dialog seems built on top of the React Native app. So it pops out everytime you call it, and doesn't to be in the render function. react-native-dialogs. An Android only module for Material Design dialogs. This is a wrapper over afollestad/material-dialogs.This module is designed for Android only with no plans to support iOS.

Use react-native-alert-async

I've just published a package that does exactly this and permit to await for the choice of the user. It is compatible with Expo.

 import AlertAsync from "react-native-alert-async";


 const myAction = async () => {

   const choice = await AlertAsync(
     'Title',
     'Message',
     [
       {text: 'Yes', onPress: () => 'yes'},
       {text: 'No', onPress: () => Promise.resolve('no')},
     ],
     {
       cancelable: true,
       onDismiss: () => 'no',
     },
   );


   if (choice === 'yes') {
     doSomething();
   }
   else {
     doSomethingElse();
   }

 }

Original answer: I've made a PR to ReactNative for this feature: https://github.com/facebook/react-native/pull/20312

How to await for the response of Alert dialog in React Native?, import AlertAsync from "react-native-alert-async"; const myAction = async () => { const choice = await AlertAsync( 'Title', 'Message', [ {text: 'Yes', onPress:  After reading this comment on the react-native GitHub issues, the following worked for me: Add the following npm module: npm install babel-preset-react-native-stage-0 --save. Add the following configuration to your .babelrc file: { presets: ['react-native-stage-0'] } Clear your cache:

I have some workaround for this,If you have alert function like below

     Alert.alert(
                'Delete comment?',
                'Are you sure you want to delete this comment?',
                [
                    {
                        text: 'Cancel',
                        onPress: () => console.log('Cancel Pressed'),
                        style: 'cancel',
                    },
                    { text: 'yes', onPress:() => this.props.deleteComment(commentId),
                ],
                { cancelable: false },
            );
  //call after comment is deleted
  refreshPage();

This code does not wait for alert's response, it will execute refreshPage() immediately.

so, you can do something like

         Alert.alert(
                    'Delete comment?',
                    'Are you sure you want to delete this comment?',
                    [
                        {
                            text: 'Cancel',
                            onPress: () => console.log('Cancel Pressed'),
                            style: 'cancel',
                        },
                        { text: 'yes', onPress: async () => {await this.props.deleteComment(commentId);refreshPage();},
                    ],
                    { cancelable: false },
                );

slorber/react-native-alert-async: An Alert.alert that you can , Launches an alert dialog with the specified title and message. Optionally provide a list of buttons. Tapping any button will fire the respective onPress callback  Dismiss Join GitHub today. GitHub is home to over 50 million developers working together to host and review code, manage projects, and build software together.

Here's a simple solution.

The trick used here is to make a function that calls the button's onPress function, then resolve the promise with the index of the button. Note that this requires the alert to be uncancellable.

showAsyncAlert = (title, message, buttons, options) => {
  return new Promise((resolve, reject) => {
    // We can't detect a cancellation, so make sure the Alert is not cancellable.
    options.cancellable = false
    buttons.forEach((button, index) => {
      let onPress = button.onPress
      button.onPress = option => {
        if (onPress) {
          onPress(option)
        }
        resolve(index)
      }
    })
    Alert.alert(title, message, buttons, options)
  })
}

Alert · React Native, Lazy dev here and we will talk about handling dialog alerts in react without tears . If you are Pretty similar to what we have in a browser with a native alert function​. In this example, once the user accepted or canceled the alert, your awaiting promise will be resolved or rejected. DELETE EDIT REPLY. react-native-dialogs. An Android only module for Material Design dialogs. This is a wrapper over afollestad/material-dialogs.This module is designed for Android only with no plans to support iOS.

The neatest way to handle alert dialogs in React 🥰, Five ways to prompt your user for input in React Native Launches an alert dialog with the specified title and message. async promptUser = () => { const selection = await new Promise((resolve) => { const title _selectUserMood() .​then(response => { const { success, data } = response; if (success) { this. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. Learn more React Native - async/await does not work

Five ways to prompt your user for input in React Native, Important: The component is meant to work as a global component. alert or window. Key Features. This is a custom component for React Native, a simple popup,  How To Use Async Await in React: an example with Promises Before starting off make sure to have a React development environment. To make one you can follow this tutorial of mine: How to set up React, webpack, and babel or you can also use create-react-app .

React dialog, Note: See Importing the JS component for more information on how to import JavaScript. If your dialog contains any layout-sensitive components, you should wait until Alert dialogs interrupt users with urgent information, details, or actions. disabled (i.e. the dialog will no longer close in response to the interaction). React Native modules. React Native has a native API for writing bridge modules that export functions to JavaScript. If these functions returned promises, we could use them as if they were async functions! It turns out that React Native is architecturally well-suited for promises.

Comments
  • The simplest way would be to store a flag if the Alert is showing, and reset it to false when it is dismissed.
  • I had similar idea in mind. But onBarCodeRead function still runs constantly in background to check the flag. I wonder if there is better way to handle this.
  • Hey, I just edited my answer because I published github.com/slorber/react-native-alert-async
  • Yes, I had the same problem. stopPreview() is deprecated in RNCamera module. I noticed that, sometimes Alert interrupts with the _onObjectDetected in RNCamera, so the barcode scanning feature completely stops after dismissing the dialog.
  • Yes it does. Tested.
  • 'await is only valid in async function', was this just recently changed? Most answers show something similar but none of these code samples actually run. Need to wrap the await in its own async function, I believe.
  • tripped into this problem again when I try to build a custom dropdown menu for react-naviagtion navbar. I will give it a try, thanks a lot
  • Works great @SebastienLorber . Your package helped me a lot! Thank you!
  • Do you think stackoverflow.com/a/52997495/2007055 is much better?
  • I ended up having the function where I display my alert in a Promise and the onPress callback is calling resolve. Thanks for the inspiration 👍