Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can React native Alert wait for user response?

Tags:

react-native

Can React native Alert wait for user's response (just like pausing the app) instead of just popup and proceed the following logic?

I think js alert will just pause the application.

like image 949
TommyQu Avatar asked Oct 15 '18 22:10

TommyQu


3 Answers

Here's what you can do with Alert:

You can set cancelable with false, so the user can't close the alert without pressing a button

You can set a callback with each button.

Also you can wrap the Alert with Promise so you can use async

const AsyncAlert = () => {
    return new Promise((resolve, reject) => {
        Alert.alert(
            'Title',
            'Message',
            [
                {text: 'YES', onPress: () => resolve('YES') },
                {text: 'NO', onPress: () => resolve('NO') }
            ],
            { cancelable: false }
        )
    })
}    

// Then to use the method
const userResponse = await AsyncAlert()
// ...the rest of your code
like image 143
Tareq El-Masri Avatar answered Oct 27 '22 07:10

Tareq El-Masri


I have taken the @Tareq El-Masri code and edited it. changing it to a async function will work.

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

await AsyncAlert();
like image 22
nanda kishore reddy Avatar answered Oct 27 '22 07:10

nanda kishore reddy


While the other answers are pretty much correct, they still require the reader to manipulate the functions to use in their own code (eg. to change buttons, etc). Here is a nice exportable version that allows you to pass in a function to create any button setup you need:

import { Alert as NativeAlert } from 'react-native';

const defaultButtons = (resolve, reject) => [
  {
    text: 'OK',
    onPress: () => {
      resolve();
    },
  },
];

const AsyncAlert = (title, msg, getButtons = defaultButtons) =>
  new Promise((resolve, reject) => {
    NativeAlert.alert(title, msg, getButtons(resolve, reject), { cancelable: false });
  });

export default AsyncAlert;

Use like this:

await AsyncAlert('Some Title', 'Some message.')

If you want custom buttons, just pass a function in as the third argument (which gets resolve and reject, should you need either.

like image 36
Matt Way Avatar answered Oct 27 '22 06:10

Matt Way