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.
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
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With