react-native#Alert JavaScript Examples

The following examples show how to use react-native#Alert. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RecordComponent.js    From react-native-todolist with MIT License 6 votes vote down vote up
openAudioLink(path) {

        setTimeout(() => {
            FileViewer.open(path)
                .then(() => {
                    // success
                    console.log("File open success")
                })
                .catch(error => {
                    // error
                    Alert.alert('Error', 'File has error - ' + error.message)
                    console.log("File open error -- " + error.message)
                });
        }, 1000);
    }
Example #2
Source File: App.js    From filen-mobile with GNU Affero General Public License v3.0 6 votes vote down vote up
setJSExceptionHandler((err, isFatal) => {
    reportError(err)

    Alert.alert("Unexpected error occured",
        `
        Error: ${err.name} ${err.message}

        The error has been automatically reported to us. Please restart the app if it does not continue to work!
        `,
        [
            {
                text: "Close",
                onPress: () => {
                    return false
                }
            }
        ]
    )
}, true)
Example #3
Source File: changePasswordScreen.js    From Baku with GNU General Public License v3.0 6 votes vote down vote up
changePassword() {

    //   changePassword = (currentPassword, newPassword) => {
    this.reauthenticate(this.state.currentPassword).then(() => {
      var user = firebase.auth().currentUser;
      user.updatePassword(this.state.newPassword).then(() => {
        Alert.alert("Password was changed");
        console.log("Password updated!");
      })
        .then(() => {
          this.props.navigation.navigate('Tabs', {
            screen: 'ProfileTab'
          }
          );
        })
      //.catch((error) => { console.log(error.message), Alert.alert(error.message); })
    }).catch((error) => { console.log(error.message), Alert.alert(error.message); });
  }
Example #4
Source File: createListing.js    From haven with MIT License 6 votes vote down vote up
function* createListingAction(action) {
  const successAction = action.payload;
  const { username, password } = yield select(getUserCredentails);
  const structuredData = yield call(generateData);
  const result = yield call(createListing, username, password, structuredData);
  if (hasIn(result, 'slug')) {
    yield put({ type: actions.resetData });
    yield put({ type: actions.actionSuccess });
    yield call(successAction, get(result, 'slug'));
    eventTracker.trackEvent('CreateListing-Created');
  } else {
    eventTracker.trackEvent('CreateListing-FailedCreation', result.reason);
    const metaType = result.reason.split('Listing_Metadata_')[1];
    yield put({ type: actions.actionFailed });
    if (metaType) {
      Alert.alert(`${metaType} is missing`);
    } else {
      Alert.alert(result.reason);
    }
  }
}
Example #5
Source File: consts.js    From guardioes-app with Apache License 2.0 6 votes vote down vote up
showSurveillanceInvite = (
    name,
    { status, body },
    func,
    navigation
) => {
    const title = translate('surveillance.titleMessage')
    const message = `${getNameParts(name)}, ${translate(
        'surveillance.message'
    )}`

    Alert.alert(title, message, [
        {
            text: translate('surveillance.cancelButton'),
            onPress: () => {
                func(status, body)
            },
        },
        {
            text: translate('surveillance.redirectButton'),
            onPress: () => {
                navigation.dispatch(
                    CommonActions.reset({
                        index: 1,
                        routes: [
                            { name: 'HomeDrawer' },
                            { name: 'Vigilancia' },
                        ],
                    })
                )
            },
        },
    ])
}
Example #6
Source File: DetectionRisk.android.js    From RRWallet with MIT License 6 votes vote down vote up
detectionRisk = () => {
  const isRoot = AppInfo.bundleId === BUNDLE_ID_PRO_ANDROID && !__DEV__ && RRRNDevice.O0o0o0OOoo00O00ooO0o0;

  if (isRoot) {
    Alert.alert("警告", "安装包有问题, 请重新安装");
  }

  return isRoot;
}
Example #7
Source File: needUpdate.js    From monsuivipsy with Apache License 2.0 6 votes vote down vote up
NeedUpdateContextProvider = ({ children }) => {
  const [needUpdate, setNeedUpdate] = useState(false);

  useEffect(() => {
    (async () => {
      const response = await API.get({ path: "/version" });
      if (response.ok && BUILD_NUMBER !== response.data.MOBILE_BUILD_NUMBER) {
        setNeedUpdate(true);
        Alert.alert(
          `La nouvelle version ${response.data.MOBILE_VERSION}(${response.data.MOBILE_BUILD_NUMBER}) de Ma Tête et Moi est disponible !`,
          `Vous avez la version ${VERSION}(${BUILD_NUMBER}) actuellement sur votre téléphone`,
          [
            {
              text: "Télécharger",
              onPress: () =>
                Linking.openURL(
                  Platform.select({
                    ios: "https://apps.apple.com/fr/app/mon-suivi-psy/id1540061393",
                    android: "https://play.google.com/store/apps/details?id=com.monsuivipsy",
                  })
                ),
            },
            { text: "Plus tard", style: "cancel" },
          ],
          { cancelable: true }
        );
      }
    })();
  }, []);

  return <NeedUpdateContext.Provider value={needUpdate}>{children}</NeedUpdateContext.Provider>;
}
Example #8
Source File: permissions.js    From duofolio with GNU General Public License v3.0 6 votes vote down vote up
getStoragePermission = async () => {
	let permissions = await PermissionsAndroid.requestMultiple(
		[
			PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
			PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE
		],
		{
			title: 'Duofolio Storage Permission',
			message: 'Duofolio needs to access your storage'
		}
	);

	if (permissions['android.permission.READ_EXTERNAL_STORAGE'] === 'granted') {
		return;
	} else {
		Alert.alert(
			'Permission required',
			'Allow Duofolio to access your storage',
			[{ text: 'OK', onPress: async () => await getStoragePermission() }],
			{ cancelable: false }
		);
	}
}
Example #9
Source File: helpers.js    From ultimate-hackathon-starting-guide with MIT License 6 votes vote down vote up
showAlert = (title, message) => {
    Alert.alert(
        title,
        message,
        [
          {
              text: 'OK',
              onPress: () => console.log('OK Pressed')
          },
        ],
        { cancelable: false }
      );
}
Example #10
Source File: Globals.js    From hugin-mobile with GNU Affero General Public License v3.0 6 votes vote down vote up
/* Note... you probably don't want to await this function. Can block for a while
   if no internet. */
export async function initGlobals() {
    const payees = await loadPayeeDataFromDatabase();

    if (payees !== undefined) {
        Globals.payees = payees;
    }

    const transactionDetails = await loadTransactionDetailsFromDatabase();

    if (transactionDetails !== undefined) {
        Globals.transactionDetails = transactionDetails;
    }

    const netInfo = await NetInfo.fetch();

    /* Start syncing */
    if ((Globals.preferences.limitData && netInfo.type === 'cellular')) {
        Alert.alert(
            'Not Syncing',
            'You enabled data limits, and are on a limited connection. Not starting sync.',
            [
                {text: 'OK'},
            ]
        );
    } else {
        Globals.wallet.start();
        Globals.wallet.enableAutoOptimization(false);
    }

    await Globals.updateNodeList();
}
Example #11
Source File: errorHandle.js    From lx-music-mobile with Apache License 2.0 6 votes vote down vote up
errorHandler = (e, isFatal) => {
  if (isFatal) {
    Alert.alert(
      '?Unexpected error occurred?',
      `
应用出bug了?,已崩溃?,以下是错误异常信息,请截图通过企鹅群或者GitHub反馈,现在应用将会关闭,请自行重新启动!

Error:
${isFatal ? 'Fatal:' : ''} ${e.name} ${e.message}
`,
      [{
        text: '关闭 (Close)',
        onPress: () => {
          exitApp()
        },
      }],
    )
  }
  log.error(e.stack)
}
Example #12
Source File: Updates.js    From real-frontend with GNU General Public License v3.0 6 votes vote down vote up
versionCheck = (async () => {
  try {
    if (Config.ENVIRONMENT !== 'production') { return }

    const isNeeded = !getReadableVersion().includes('1.1.0')

    if (isNeeded) {
      Alert.alert(
        'App Update Available',
        'Please update REAL to continue proceeding',
        [{
          text: 'Done',
          onPress: () => Linking.openURL('https://apps.apple.com/us/app/real-social-media/id1485194570?ls=1').catch(console.log),
          style: 'cancel',
        }],
        { cancelable: false },
      )
    }
  } catch (error) {
  }
})
Example #13
Source File: Alert.js    From id.co.moonlay-eworkplace-mobile with MIT License 6 votes vote down vote up
exitAlert = () => {
  Alert.alert(
    'Confirm exit',
    'Do you want to quit the app?'
    [
      {text: 'CANCEL',onPress: () =>{} ,style: 'cancel'},
      {text: 'OK', onPress: () => BackHandler.exitApp()}
    ]
  );
}
Example #14
Source File: ContactSellerForm.js    From Done-With-It with MIT License 6 votes vote down vote up
function ContactSellerForm({ listing }) {
	const handleSubmit = async ({ message }, { resetForm }) => {
		Keyboard.dismiss();

		const result = await messagesApi.send(message, listing.id);

		if (!result.ok) {
			console.log("Error", result);
			return Alert.alert(
				"Error",
				"Could not send the message to the seller."
			);
		}

		resetForm();

		Notifications.presentLocalNotificationAsync({
			title: "Awesome!",
			body: "Your message was sent to the seller.",
		});
	};

	return (
		<Form
			initialValues={{ message: "" }}
			onSubmit={handleSubmit}
			validationSchema={validationSchema}
		>
			<FormField
				maxLength={255}
				multiline
				name="message"
				numberOfLines={3}
				placeholder="Message..."
			/>
			<SubmitButton title="Contact Seller" />
		</Form>
	);
}
Example #15
Source File: ScannerScreen.js    From pineapple-reactNative with MIT License 6 votes vote down vote up
renderAlert(title, message) {
    Alert.alert(
      title,
      message,
      [
        { text: 'OK', onPress: () => this.resetScanner() },
      ],
      { cancelable: true }
    );
  }
Example #16
Source File: NfcProxy.js    From react-native-nfc-rewriter with MIT License 6 votes vote down vote up
handleException = (ex) => {
  if (ex instanceof NfcError.UserCancel) {
    // bypass
  } else if (ex instanceof NfcError.Timeout) {
    Alert.alert('NFC Session Timeout');
  } else {
    console.warn(ex);

    if (Platform.OS === 'ios') {
      NfcManager.invalidateSessionWithErrorIOS(`${ex}`);
    } else {
      Alert.alert('NFC Error', `${ex}`);
    }
  }
}
Example #17
Source File: PostOptions.js    From Cosmos with MIT License 6 votes vote down vote up
PostOptions = ({isOpen, closeSheet, goBack, box, postName}) => {
  return (
    <BottomSheet
      isOpen={isOpen}
      closeBottomSheet={() => closeSheet()}
      options={[
        {
          text: 'Delete',
          onPress: () => {
            closeSheet();
            onDelete(box, postName, goBack);
          },
        },
        {
          text: 'Share',
          onPress: () => {
            onShare(box + '@@@' + postName.split('.')[0], (message) => {
              Alert.alert('Error', message, [{text: 'ok'}], {
                cancelable: true,
              });
            });
            closeSheet();
          },
        },
      ]}
    />
  );
}
Example #18
Source File: GameHome.js    From FlappyFace with MIT License 6 votes vote down vote up
onLogout() {
    Alert.alert(
      'Logout',
      'Are you sure, you want to logout of the app?',
      [
        {
          text: 'Yes',
          onPress: async () => {
            await GoogleSignin.revokeAccess();
            await GoogleSignin.signOut();
            auth().signOut();
          },
        },
        {text: 'No'},
      ],
      {cancelable: true},
    );
  }
Example #19
Source File: NfcWrapper.js    From sdk-samples with Apache License 2.0 6 votes vote down vote up
printResults = (error, result) => {
    if (error != null) {
        Alert.alert(
            'Error',
            error,
            [
                {text: 'OK', onPress: () => console.log('OK Pressed')},
            ],
            {cancelable: false}
        );
    } else {

        Alert.alert(
            'Response from card',
            result,
            [
                {text: 'OK', onPress: () => console.log('OK Pressed')},
            ],
            {cancelable: false}
        );
    }
}
Example #20
Source File: App.js    From redis-examples with MIT License 6 votes vote down vote up
async componentDidMount() {
    var version = await EncryptedStorage.getItem('announcement_version');
    if(version == null){
      version = "-1";
    }
    version = parseInt(version);
    console.log(version)
    await fetch('https://us1-sharing-dassie-35422.upstash.io/zrangebyscore/Announcements/+inf/' + version + "/WITHSCORES/LIMIT/0/1", {
        method: 'GET',
        headers: {
          Authorization: "Bearer AopeACQgZGQwNDA5ODktMmEzYy00NmM5LTg4MTQtM2U4NTQ5OTMxZTEySVgyTr4DQTX0HnyHo-YWG1xRXdr64-EngpCYIHhanJY=",
          Accept: 'application/json',
          'Content-Type': 'application/json'
        }
      })
      .then(response => response.json())
      .then(data => {
        var announcement = data["result"];
        if(announcement && announcement.length > 0){
          version = parseInt(announcement[1]) + 1;
          var message = announcement[0];
          EncryptedStorage.setItem('announcement_version', version.toString());
          Alert.alert("You have new message!", message);
        }
        console.log(data);
      })
      .catch(err => {
        console.error(err)
      });
  }
Example #21
Source File: loginSaga.js    From MediBuddy with MIT License 6 votes vote down vote up
// Our worker Saga that logins the user
export default function* loginAsync() {
  yield put(loginActions.enableLoader());

  //how to call api
  //const response = yield call(loginUser, action.username, action.password);
  //mock response
  const response = { success: true, data: { id: 1 } };

  if (response.success) {
    yield put(loginActions.onLoginResponse(response.data));
    yield put(loginActions.disableLoader({}));
    yield call(navigationActions.resetToHome);
  } else {
    yield put(loginActions.loginFailed());
    yield put(loginActions.disableLoader({}));
    setTimeout(() => {
      Alert.alert('BoilerPlate', response.Message);
    }, 200);
  }
}
Example #22
Source File: Blog.js    From Get-Placed-App with MIT License 5 votes vote down vote up
export default function JobList(props) {
    const [data, setdata] = useState([])
    const [loading, setLoading] = useState(true)

    const loadData = () => {
        fetch('https://getplaced.pythonanywhere.com/api/blog/', {
            method: "GET"
        })
            .then(resp => resp.json())
            .then(data => {
                setdata(data)
                setLoading(false)
            })
            .catch(error => Alert.alert("error", error))
    }

    useEffect(() => {
        loadData();
    }, [])

    const clickedItem = (data) => {
        props.navigation.navigate("Blog-Detail", { data: data })
    }

    const renderData = (item) => {
        var date = new Date(`${item.post_date}`)
        return (
            <>
                <Card style={styles.cardStyle} onPress={() => clickedItem(item)}>
                    <View style={{ flex: 1 }}>
                        <Text
                            onPress={() => clickedItem(item)}
                            style={{ color: "#000", fontSize: 16, marginLeft: 15, }}>
                            {item.title}
                            <Text style={{ fontSize: 13, color: '#808080' }}>    -   ({date.getDate()}-{date.getMonth()}-{date.getFullYear()})</Text>
                        </Text>
                        <Text
                            onPress={() => clickedItem(item)}
                            style={{ color: "#808080", fontSize: 12, marginLeft: 17, }}>
                            {item.snippet}
                        </Text>

                    </View>
                </Card>
            </>
        )
    }
    return (
        <View>
            <FlatList
                data={data}
                renderItem={({ item }) => {
                    return renderData(item)
                }}
                onRefresh={() => loadData()}
                refreshing={loading}
                keyExtractor={item => `${item.id}`}
            />
            <FAB
                style={styles.fab}
                small={false}
                icon="plus"

                onPress={() => props.navigation.navigate("Create")}
            />
        </View>


    )
}
Example #23
Source File: map.js    From Solution-Starter-Kit-Cooperation-2020 with Apache License 2.0 5 votes vote down vote up
Map = (props) => {
  const webView = useRef(null);

  const onMessage = (event) => {
    const message = JSON.parse(event.nativeEvent.data);

    if (message.status && message.status === 'initialized') {
      Geolocation.getCurrentPosition((position) => {
        sendMessage(position);
      });

      if (props.route.params && props.route.params.item) {
        sendMessage({ item: props.route.params.item });
      }
    } else if (message.search) {
      search(message.search)
        .then((response) => {
          sendMessage({ search: response });
        })
        .catch(err => {
          console.log(err)
          Alert.alert('ERROR', 'Please try again. If the problem persists contact an administrator.', [{text: 'OK'}]);
        });
    }
  };

  const sendMessage = (data) => {
    const message = 
      `(function() {
        document.dispatchEvent(new MessageEvent('message', {data: ${JSON.stringify(data)}}));
      })()`;

    webView.current.injectJavaScript(message);
  }

  const sourceUri = (Platform.OS === 'android' ? 'file:///android_asset/' : '') + 'Web.bundle/loader.html';
  const injectedJS = `
    if (!window.location.search) {
      var link = document.getElementById('progress-bar');
      link.href = './site/here.html?apikey=${hereApikey}';
      link.click();
    }
  `;

  return (
    <View style={styles.mapContainer}>
      <WebView          
        injectedJavaScript={injectedJS}
        source={{ uri: sourceUri }}
        javaScriptEnabled={true}
        originWhitelist={['*']}
        allowFileAccess={true}
        onMessage={onMessage}
        ref={webView}
      />
    </View>
  );
}
Example #24
Source File: Feedback.js    From timetable with MIT License 5 votes vote down vote up
Feedback = () => {
  const navigation = useNavigation()
  const { t } = useTranslation()
  const { theme } = useTheme()

  const sendEmailHandler = ({ name, email, message }) => {
    const data = JSON.stringify({ name, email, message }).replace(/[{}'']/g, '')

    fetch('https://api.sendgrid.com/v3/mail/send', {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json',
        Authorization: 'Bearer ' + process.env.API_SEND_GRID_KEY
      },
      body: JSON.stringify({
        personalizations: [
          {
            to: [
              {
                email: process.env.SEND_GRID_EMAIL_TO
              }
            ],
            subject: 'Bus Timetable Feedback'
          }
        ],
        from: {
          email: process.env.SEND_GRID_EMAIL_FROM
        },
        content: [
          {
            type: 'text/plain',
            value: data
          }
        ]
      })
    })
      .then(() => {
        Alert.alert('', t('feedback.onSuccessfulSubmit'), [
          {
            text: t('feedback.cancel'),
            onPress: () => navigation.navigate('About')
          }
        ])
      })
      .catch(() => {
        Alert.alert(t('feedback.error'), t('feedback.onSubmitError'), [
          { text: t('feedback.cancel') }
        ])
      })
  }

  return (
    <TouchableWithoutFeedback onPress={() => Keyboard.dismiss()}>
      <View style={styles.container}>
        <Text style={[styles.info, { color: theme.text }]}>
          {t('feedback.info')}
        </Text>
        <ScrollView style={styles.form}>
          <Form
            onSubmitHandler={sendEmailHandler}
            namePlaceholder={t('feedback.namePlaceholder')}
            emailPlaceholder={t('feedback.emailPlaceholder')}
            messagePlaceholder={t('feedback.messagePlaceholder')}
            submitTitle={t('feedback.submitTitle')}
            schemaRequiredName={t('feedback.schemaRequiredName')}
            schemaRequiredEmail={t('feedback.schemaRequiredEmail')}
            schemaRequiredMessage={t('feedback.schemaRequiredMessage')}
            buttonColor={theme.buttonColor}
            buttonText={theme.buttonText}
          />
        </ScrollView>
      </View>
    </TouchableWithoutFeedback>
  )
}
Example #25
Source File: detail.js    From perform-2020-hotday with Apache License 2.0 5 votes vote down vote up
//ToDo
//import { Dynatrace, Platform } from '@dynatrace/react-native-plugin';

export default function Detail(props) {

  const movie = props.navigation.getParam('movie', null);
  let token=null;
  const [ highlight, setHeighlight] = useState(0); 

  const getData = async () => {
    token = await AsyncStorage.getItem('MR_Token');
    if (token) {
      console.log("+++++++++++++ Token retrieved= " + token);
    } else {
      console.log("************* No token found ************");
    }
  };
  
  const rateClicked = () => {
    getData();
    if(highlight > 0 && highlight < 6){ 
      //ToDo
      //Dynatrace.reportIntValue("Stars",  highlight);
      fetch(`http://www.dynatraceworkshops.com:8079/api/movies/${movie.id}/rate_movie/`, {
      method: 'POST',
      headers: {
        'Authorization': `Token ad99a678759cb7c771457680a6cc68cbec062de9`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ stars: highlight})
    })
    .then( res => res.json())
    .then( res => {
      setHeighlight(0);
      Alert.alert("Rating", res.message);
    })
    .catch( error => Alert.alert("Error", error));
    }
  }

  return (
    <View style={styles.container}>
      <View style={styles.starContainer}>
        <FontAwesomeIcon style={movie.avg_rating > 0 ? styles.orange : styles.white} icon={faStar}/>
        <FontAwesomeIcon style={movie.avg_rating > 1 ? styles.orange : styles.white} icon={faStar}/>
        <FontAwesomeIcon style={movie.avg_rating > 2 ? styles.orange : styles.white} icon={faStar}/>
        <FontAwesomeIcon style={movie.avg_rating > 3 ? styles.orange : styles.white} icon={faStar}/>
        <FontAwesomeIcon style={movie.avg_rating > 4 ? styles.orange : styles.white} icon={faStar}/>
        <Text style={styles.white}>({movie.no_of_ratings})</Text>
      </View>
      <Text style={styles.description}>{movie.description}</Text>

      <View style={{borderBottomColor: 'white', borderBottomWidth: 2}}/>
      <Text style={styles.description}>Rate it !!!</Text>

      <View style={styles.starContainer}>
        <FontAwesomeIcon style={highlight > 0 ? styles.purple : styles.grey} icon={faStar} size={48} onPress={()=> setHeighlight(1)}/>
        <FontAwesomeIcon style={highlight > 1 ? styles.purple : styles.grey} icon={faStar} size={48} onPress={()=> setHeighlight(2)}/>
        <FontAwesomeIcon style={highlight > 2 ? styles.purple : styles.grey} icon={faStar} size={48} onPress={()=> setHeighlight(3)}/>
        <FontAwesomeIcon style={highlight > 3 ? styles.purple : styles.grey} icon={faStar} size={48} onPress={()=> setHeighlight(4)}/>
        <FontAwesomeIcon style={highlight > 4 ? styles.purple : styles.grey} icon={faStar} size={48} onPress={()=> setHeighlight(5)}/>
      </View>
      <Button title="Rate" onPress={() => rateClicked()}/>
    </View>
  );
}
Example #26
Source File: order.js    From haven with MIT License 5 votes vote down vote up
delayedAlert = message => setTimeout(() => Alert.alert(message), 1500)
Example #27
Source File: App.js    From guardioes-app with Apache License 2.0 5 votes vote down vote up
Guardioes = () => {
    const [isSubscribed, setIsSubscribed] = useState(null)

    useEffect(() => {
        const initOneSignal = async () => {
            /* ONESIGNAL SETUP */
            OneSignal.setAppId(ONESIGNAL_APP_ID)
            OneSignal.setLogLevel(5, 0)
            OneSignal.promptForPushNotificationsWithUserResponse((response) => {
                console.log('Prompt response:', response)
            })

            /* ONESIGNAL HANDLERS */
            OneSignal.setNotificationWillShowInForegroundHandler(
                (notifReceivedEvent) => {
                    console.log(
                        'OneSignal: notification will show in foreground:',
                        notifReceivedEvent
                    )
                    const notif = notifReceivedEvent.getNotification()

                    const button1 = {
                        text: 'Cancel',
                        onPress: () => {
                            notifReceivedEvent.complete()
                        },
                        style: 'cancel',
                    }

                    const button2 = {
                        text: 'Confirm',
                        onPress: () => {
                            notifReceivedEvent.complete(notif)
                        },
                    }

                    Alert.alert(notif.title, notif.body, [button1, button2], {
                        cancelable: false,
                    })
                }
            )
            OneSignal.setNotificationOpenedHandler((notification) => {
                console.log('OneSignal: notification opened:', notification)
            })
            OneSignal.addSubscriptionObserver((event) => {
                console.log('OneSignal: subscription changed:', event)
                setIsSubscribed(event.to.isSubscribed)
            })
            OneSignal.addPermissionObserver((event) => {
                console.log('OneSignal: permission changed:', event)
            })

            const deviceState = await OneSignal.getDeviceState()
            setIsSubscribed(deviceState.isSubscribed)
        }

        initOneSignal()
    }, [])

    return (
        <NavigationContainer>
            <AppProvider>
                <Routes />
            </AppProvider>
        </NavigationContainer>
    )
}
Example #28
Source File: ImportHDWalletScreen.js    From RRWallet with MIT License 5 votes vote down vote up
isVaildInput() {
    this.name = this.name.trim();

    let isEnglish = false;
    let isChinese = false;
    const str = this.word.split(" ").join(""); //去除空格
    for (let i = 0; i < str.length; i++) {
      const charCode = str.charCodeAt(i);
      if (charCode >= 0x4e00 && charCode <= 0x9fef) {
        isChinese = true;
      } else if (charCode >= 97 && charCode <= 122) {
        isEnglish = true;
      } else {
        Alert.alert("", `${String.fromCharCode(charCode)}是非法字符`);
        return false;
      }
      if (isEnglish && isChinese) {
        Alert.alert("", i18n.t("wallet-recovery-invaild"));
        return false;
      }
      if (!isEnglish && !isChinese) {
        Alert.alert("", i18n.t("wallet-recovery-invaild"));
        return false;
      }
    }

    const words = isEnglish
      ? this.word.split(" ")
      : this.word
          .split(" ")
          .join("")
          .split("");
    if (words.length != 12 && words.length != 15) {
      Alert.alert("", i18n.t("wallet-recovery-invaild"));
      return false;
    }

    for (let i = 0; i < words.length; i++) {
      const word = words[i];
      if (!MnemonicWordsEnglish.hasOwnProperty(word) && !MnemonicWordsChinese.hasOwnProperty(word)) {
        Alert.alert("", `${word}${i18n.t("wallet-recovery-word-invaild")}`);
        return false;
      }
    }

    this.word = words.join(" ");
    if (!this.name || !this.name.length) {
      Alert.alert("", "钱包名称不能为空");
      return false;
    }
    if (this.name.length > 20) {
      Alert.alert("", "钱包名称不能大于20个字");
      return false;
    }
    // if (this.isImport && AccountStore.accounts.find(account => account.name == this.name)) {
    //     Alert.alert('','已存在相同名称的钱包')
    //     return false
    // }

    let flag = PasswordUtil.checkPasswordWithTip(this.pwd, this.repwd);
    return flag;
  }
Example #29
Source File: index.js    From atendimento-e-agilidade-medica-AAMed with MIT License 5 votes vote down vote up
export default function ForgotPasword() {
  const [email, setEmail] = useState('');
  const navigation = useNavigation();

  function handleSubmit() {
    if (email === '') {
      return Alert.alert('Aviso', 'Preencha o campo de e-mail.');
    }
    console.log(email);
  }

  return (
    <Keyboard keyboardVerticalOffset={0} behavior="padding" enabled={false}>
      <Container>
        <TopContainer>
          <Title>Esqueceu a senha?</Title>
          <BoxDescription>
            <Description>
              {`Digite seu endereço de e-mail
        e enviaremos um link
      para redefinir sua senha`}
            </Description>
          </BoxDescription>
        </TopContainer>

        <View>
          <Label>E-mail</Label>
          <Input
            autoFocus
            autoCapitalize="none"
            placeholder="[email protected]"
            placeholderTextColor="#00000066"
            keyboardType="email-address"
            selectionColor="#006bad66"
            onChangeText={setEmail}
            value={email}
          />

          <MainButton
            onPress={() => handleSubmit()}
            label={'Recuperar senha'}
          />
        </View>

        <BottomContainer>
          <BottomContainerText>Não tem uma conta?</BottomContainerText>
          <TouchableOpacity onPress={() => navigation.navigate('SignUp')}>
            <BottomContainerTextTouch>Cadastre-se</BottomContainerTextTouch>
          </TouchableOpacity>
        </BottomContainer>
      </Container>
    </Keyboard>
  );
}