Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.
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?

like image 686
FisNaN Avatar asked Feb 15 '18 14:02

FisNaN


People also ask

How do I use alert prompt in react native?

React Native Alert is an API which is used to display an alert dialog with specified title and message. It uses an alert() method to prompt an alert dialog. This Alert dialog provides three different lists of buttons (combination of neutral, negative, and positive) to perform action.

How do I show alert dialog in react?

The Alert component helps to show a dialog box i.e., a pop up to the user with a title, message, buttons to know the confirmation from the user based on the message displayed. import { Alert } from 'react-native'; To get the pop-up you just have to call the Alert. alert() function.

How do I dismiss alert dialog in react native?

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 and dismiss the alert.


2 Answers

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();
like image 188
nanda kishore reddy Avatar answered Oct 15 '22 14:10

nanda kishore reddy


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

like image 43
Sebastien Lorber Avatar answered Oct 15 '22 14:10

Sebastien Lorber