react-native#Alert TypeScript 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: App.tsx    From companion-kit with MIT License 6 votes vote down vote up
private async showDevAlert() {
        if (!AppController.Instance.version.isDevelopment) {
            return;
        }

        const hasConfirmedDev = await AsyncStorage.getValue(CONFIRM_DEV_KEY);
        if (hasConfirmedDev) {
            return;
        }

        Alert.alert(
            'Warning',
            'This is development version of the app. Changes you will make may be lost or corrupted.',
            [
                {
                    text: 'OK',
                    style: 'cancel',
                },
                {
                    text: 'Don\'t show again',
                    style: 'destructive',
                    onPress: async () => {
                        await AsyncStorage.setValue(CONFIRM_DEV_KEY, 'true');
                    },
                },
            ],
        );
    }
Example #2
Source File: appReviewer.tsx    From SQL-Play with GNU Affero General Public License v3.0 6 votes vote down vote up
showReviewAlert = () => {
  Alert.alert(
    'Enjoying the App ?',
    'Give a review for SQL Playground',
    [
      {
        text: 'No Thanks',
        onPress: async () => await setAppData(userActionId, 'denied'),
        style: 'cancel',
      },
      {
        text: 'Rate 5 ?',
        onPress: () => launchReview(),
      },
    ],
    {cancelable: true},
  );
}
Example #3
Source File: checkUpdate.ts    From THUInfo with MIT License 6 votes vote down vote up
checkBroadcast = () => {
	getBroadcastData().then((r) => {
		if (r.length > 0) {
			Alert.alert(
				getStr("broadcast"),
				r.map((it) => it.message).join("\n"),
				[
					{
						text: getStr("confirm"),
						onPress: () =>
							store.dispatch(configSet("lastBroadcast", r[0].createdAt)),
					},
				],
				{cancelable: true},
			);
		}
	});
}
Example #4
Source File: App.tsx    From react-native-stepper-ui with MIT License 6 votes vote down vote up
App = () => {
  const [active, setActive] = useState(0);

  return (
    <View style={{ marginVertical: 80, marginHorizontal: 20 }}>
      <Stepper
        active={active}
        content={content}
        onBack={() => setActive((p) => p - 1)}
        onFinish={() => Alert.alert('Finish')}
        onNext={() => setActive((p) => p + 1)}
      />
    </View>
  );
}
Example #5
Source File: ContextMenuViewExample13.tsx    From react-native-ios-context-menu with MIT License 6 votes vote down vote up
export function ContextMenuViewExample13(props: ContextMenuExampleProps) {
  return (
    <ContextMenuView
      style={props.style}
      menuConfig={{
        menuTitle: 'ContextMenuViewExample13',
        menuItems: [{
          actionKey: 'key-01',
          actionTitle: 'Action #1',
          discoverabilityTitle: 'Action subtitle',
        }, {
          actionKey: 'key-02'   ,
          actionTitle: 'Action #2',
          actionSubtitle: 'Lorum ipsum sit amit dolor aspicing',
        }, {
          actionKey: 'key-03'   ,
          actionTitle: 'Action #3',
          actionSubtitle: 'Very long `discoverabilityTitle` lorum ipsum sit amit',
        }],
      }}
      onPressMenuItem={({nativeEvent}) => {
        Alert.alert(
          'onPressMenuItem Event',
          `actionKey: ${nativeEvent.actionKey} - actionTitle: ${nativeEvent.actionTitle}`
        );
      }}
    >
      <ContextMenuCard
        index={props.index}
        title={'ContextMenuViewExample13'}
        subtitle={'discoverabilityTitle'}
        description={[
          `Context menu with 3 actions that has the 'discoverabilityTitle' set.`
        ]}
      />
    </ContextMenuView>
  );
}
Example #6
Source File: imagePickerHandler.ts    From lexicon with MIT License 6 votes vote down vote up
export async function imagePickerHandler(
  extensions: Array<string> | undefined,
) {
  let stringifyExtensions = extensions?.toString();
  let result = await pickImage(extensions);

  switch (result.error) {
    case 'format': {
      Alert.alert(
        t('Failed!'),
        t(
          `Please upload image with a suitable format in {stringifyExtensions}`,
          {
            stringifyExtensions,
          },
        ),
        [{ text: t('Got it') }],
      );
      return;
    }
    case 'denied': {
      Alert.alert(
        t('Photo Permissions Required'),
        t(
          `Please adjust your phone's settings to allow the app to access your photos.`,
        ),
        [{ text: t('Got it') }],
      );
      return;
    }
    case 'cancelled': {
      return;
    }
  }

  return result;
}
Example #7
Source File: RootErrorBoundary.tsx    From react-native-template with MIT License 6 votes vote down vote up
showError = () => {
    Alert.alert(
      this.state.error?.name || "Error",
      this.state.error?.stack || RootErrorBoundary.NO_STACK,
      [
        {
          text: "Cancel",
          onPress: () => {
            return
          },
        },
        {
          text: "Copy & Open Issue Form",
          onPress: () => {
            const stackTrace =
              this.state.error?.stack || RootErrorBoundary.NO_STACK

            Clipboard.setString(stackTrace)

            Linking.openURL(RootErrorBoundary.ISSUE_REPORTING_URL)
          },
        },
      ],
      {
        cancelable: false,
      }
    )
  }
Example #8
Source File: phone.ts    From lets-fork-native with MIT License 6 votes vote down vote up
call = (phone: string): void => {
  let phoneNumber: string
  if (Platform.OS !== 'android') {
    phoneNumber = `telprompt:${phone}`
  } else {
    phoneNumber = `tel:${phone}`
  }
  Linking.canOpenURL(phoneNumber)
    .then((supported) => {
      if (!supported) {
        Alert.alert('Phone number is not available')
      } else {
        return Linking.openURL(phoneNumber)
      }
      return null
    })
    .catch((err) => console.log(err))
}
Example #9
Source File: loginPrompt.ts    From magento_react_native_graphql with MIT License 6 votes vote down vote up
showLoginPrompt = (
  message: string,
  navigation: StackNavigationProp<AppStackParamList>,
): void => {
  Alert.alert(
    translate('common.dearUser'),
    message,
    [
      {
        text: translate('common.login'),
        onPress: () =>
          navigation.navigate(
            Routes.NAVIGATION_TO_AUTHENTICATION_SPLASH_SCREEN,
            { screen: Routes.NAVIGATION_TO_LOGIN_SCREEN },
          ),
      },
      {
        text: translate('common.signup'),
        onPress: () =>
          navigation.navigate(
            Routes.NAVIGATION_TO_AUTHENTICATION_SPLASH_SCREEN,
            { screen: Routes.NAVIGATION_TO_SIGNUP_SCREEN },
          ),
      },
    ],
    { cancelable: true },
  );
}
Example #10
Source File: helpers.ts    From stripe-react-native with MIT License 6 votes vote down vote up
export async function fetchPublishableKey(
  paymentMethod?: string
): Promise<string | null> {
  try {
    const response = await fetch(
      `${API_URL}/stripe-key?paymentMethod=${paymentMethod}`
    );

    const { publishableKey } = await response.json();

    return publishableKey;
  } catch (e) {
    console.warn('Unable to fetch publishable key. Is your server running?');
    Alert.alert(
      'Error',
      'Unable to fetch publishable key. Is your server running?'
    );
    return null;
  }
}
Example #11
Source File: DataSharing.tsx    From mobile with Apache License 2.0 5 votes vote down vote up
DataSharingScreen = () => {
  const navigation = useNavigation();
  const [i18n] = useI18n();
  const close = useCallback(() => navigation.goBack(), [navigation]);
  const [exposureStatus] = useExposureStatus();
  const [codeValue, setCodeValue] = useState('');
  const handleChange = useCallback(text => setCodeValue(text), []);
  // if keySubmissionStatus is None we need the 1-time code, otherwise we should go right to consent
  const [isVerified, setIsVerified] = useState(exposureStatus.type === 'diagnosed');
  const onError = useCallback(() => {
    Alert.alert(i18n.translate('DataUpload.ErrorTitle'), i18n.translate('DataUpload.ErrorBody'), [
      {text: i18n.translate('DataUpload.ErrorAction')},
    ]);
    setIsVerified(false);
  }, [i18n]);
  const handleVerify = useCallback(async () => {
    setIsVerified(true);
  }, []);

  const handleUploaded = useCallback(() => {
    navigation.goBack();
  }, [navigation]);

  return (
    <Box backgroundColor="overlayBackground" flex={1}>
      <SafeAreaView style={styles.flex}>
        <Toolbar
          title={isVerified ? i18n.translate('DataUpload.ConsentTitle') : ''}
          navIcon="icon-back-arrow"
          navText={i18n.translate('DataUpload.Cancel')}
          navLabel={i18n.translate('DataUpload.Cancel')}
          onIconClicked={close}
        />
        <ScrollView style={styles.flex} keyboardShouldPersistTaps="handled">
          {!isVerified && (
            <FormView value={codeValue} onChange={handleChange} onSuccess={handleVerify} onError={onError} />
          )}
          {isVerified && <ConsentView onSuccess={handleUploaded} onError={onError} />}
        </ScrollView>
      </SafeAreaView>
    </Box>
  );
}
Example #12
Source File: PictureViewViewModel.ts    From companion-kit with MIT License 5 votes vote down vote up
public pickImage = async (options?: ImagePicker.ImagePickerOptions) => {
        await this.askCameraRollPermissions();

        if (!this.cameraRollPermission) {
            Alert.alert(
                'Oops',
                'Looks like camera roll access have been restricted. Please re-enable it anytime in Settings and try again.',
                [
                    { text: 'Cancel' },
                    {
                        text: 'Settings',
                        onPress: async () => {
                            const url = 'app-settings:';
                            await Links.tryOpenLink(url);
                        },
                        style: 'default',
                    },
                ]);
            return false;
        }

        const result = await ImagePicker.launchImageLibraryAsync(options);

        if (result.cancelled === true) {
            return false;
        }

        const fileInfo = await FileSystem.getInfoAsync(result.uri, { size: true });
        if (!fileInfo.exists) {
            return false;
        }
        if (fileInfo.size > maxFileSizeToMB) {
            Alert.alert('Sorry', `Unfortunately we can\'t process file more than ${maxFileSize} MB. Please crop it or compress in your OS.`);
            return false;
        }

        const pic = await this.resizePic(result, true);

        return pic;
    }
Example #13
Source File: ErrorService.ts    From hamagen-react-native with MIT License 5 votes vote down vote up
onError = ({ error, dispatch, actionType, customAction, showError, messageToShow }: ErrorService) => {
  console.log(error);
  !!dispatch && dispatch({ type: actionType });
  customAction && customAction();
  storeFactory().dispatch({ type: TOGGLE_LOADER, payload: { isShow: false } });
  showError && messageToShow && Alert.alert(messageToShow);
}
Example #14
Source File: leave.tsx    From protect-scotland with Apache License 2.0 5 votes vote down vote up
Leave: FC = () => {
  const {t} = useTranslation();
  const exposure = useExposure();
  const app = useApplication();
  const navigation = useNavigation();
  const {reload} = useSettings();
  const reminder = useReminder();

  const confirmed = async () => {
    try {
      try {
        await exposure.deleteAllData();
        exposure.stop();
      } catch (err) {
        console.log(err);
      }
      await forget();
      await app.clearContext();
      reminder.deleteReminder();
      reload();

      Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success);

      navigation.reset({
        index: 0,
        routes: [{name: ScreenNames.ageConfirmation}]
      });
    } catch (e) {
      Haptics.notificationAsync(Haptics.NotificationFeedbackType.Error);
      Alert.alert(
        'Error',
        e.message && e.message === 'Network Unavailable'
          ? t('common:networkError')
          : t('leave:error')
      );
    }
  };

  const confirm = () => {
    Alert.alert(t('leave:confirm:title'), t('leave:confirm:text'), [
      {
        text: t('leave:confirm:cancel'),
        onPress: () => console.log('Cancel Pressed'),
        style: 'cancel'
      },
      {
        text: t('leave:confirm:confirm'),
        onPress: () => confirmed(),
        style: 'destructive'
      }
    ]);
  };

  return (
    <>
      <StatusBar barStyle="default" />
      <ScrollView style={styles.container}>
        <Back variant="light" />
        <Spacing s={44} />
        <Title accessible title="leave:title" />
        <Markdown>{t('leave:body')}</Markdown>
        <Button
          style={styles.button}
          hint={t('leave:control:hint')}
          label={t('leave:control:label')}
          onPress={confirm}>
          {t('leave:control:label')}
        </Button>
        <Spacing s={44} />
      </ScrollView>
    </>
  );
}
Example #15
Source File: ecard.tsx    From THUInfo with MIT License 5 votes vote down vote up
performLoseCard = () => {
	Alert.alert(
		getStr("confirmLoseCard"),
		getStr("loseCardCannotBeUndone"),
		[
			{
				text: getStr("cancel"),
				style: "cancel",
			},
			{
				text: getStr("confirm"),
				onPress: () => {
					helper
						.loseCard()
						.then((value) => {
							// Why setTimeOut? https://github.com/cooperka/react-native-snackbar/issues/28
							setTimeout(() => {
								if (value === 2) {
									Snackbar.show({
										text: "挂失成功!",
										duration: Snackbar.LENGTH_SHORT,
									});
								} else {
									const valueToText = new Map<number, string>([
										[4, "您的卡片已经处于挂失状态,请不要重复挂失!"],
										[5, "卡片状态无效,无法挂失!"],
										[-1, "挂失处理失败,没有此卡信息,请联系卡务中心!"],
										[-2, "挂失处理失败,此卡有效期错误,请联系卡务中心!"],
										[
											-100,
											"挂失处理失败,学校服务器数据库错误,请联系卡务中心!",
										],
										[
											7,
											"挂失处理失败,学校服务器挂失服务异常,请联系卡务中心!",
										],
									]);
									Snackbar.show({
										text:
											valueToText.get(value) ??
											`挂失处理失败,未知错误[错误代码:${value}],请联系卡务中心!`,
										duration: Snackbar.LENGTH_INDEFINITE,
										action: {text: getStr("ok")},
									});
								}
							}, 100);
						})
						.catch(() =>
							setTimeout(() => {
								Snackbar.show({
									text: getStr("networkRetry"),
									duration: Snackbar.LENGTH_SHORT,
								});
							}, 100),
						);
				},
			},
		],
		{cancelable: true},
	);
}
Example #16
Source File: App.tsx    From SQUID with MIT License 5 votes vote down vote up
componentDidMount() {
    this.load().catch((err) => {
      console.log('err', err)
      Alert.alert('Load app failed')
    })
  }
Example #17
Source File: ClearExposureView.tsx    From mobile with Apache License 2.0 5 votes vote down vote up
ClearExposureView = () => {
  const i18n = useI18n();
  const [clearExposedStatus] = useClearExposedStatus();
  const onClearExposedState = useCallback(() => {
    Alert.alert(i18n.translate('Home.ExposureDetected.Dismiss.Confirm.Body'), undefined, [
      {
        text: i18n.translate('Home.ExposureDetected.Dismiss.Confirm.Cancel'),
        onPress: () => {},
        style: 'cancel',
      },
      {
        text: i18n.translate('Home.ExposureDetected.Dismiss.Confirm.Accept'),
        onPress: () => {
          clearExposedStatus();
        },
        style: 'default',
      },
    ]);
  }, [clearExposedStatus, i18n]);
  return (
    <Box>
      <Text variant="bodyTitle" marginBottom="m" accessibilityRole="header">
        {i18n.translate('Home.ExposureDetected.Dismiss.Title')}
      </Text>

      <Text marginBottom="m">
        <Text>{i18n.translate('Home.ExposureDetected.Dismiss.Body')}</Text>
      </Text>

      <Box alignSelf="stretch" marginTop="s" marginBottom="m">
        <ButtonSingleLine
          iconName="icon-check-white"
          text={i18n.translate('Home.ExposureDetected.Dismiss.CTA')}
          onPress={onClearExposedState}
          variant="bigFlatPurple"
        />
      </Box>
    </Box>
  );
}
Example #18
Source File: ContextMenuButtonExample01.tsx    From react-native-ios-context-menu with MIT License 5 votes vote down vote up
export function ContextMenuButtonExample01(props: ContextMenuExampleProps) {
  return (
    <ContextMenuButtonCard
      style={props.style}
      index={props.index}
      title={'ContextMenuButtonExample01'}
      subtitle={'actions text-only'}
      description={[
        `Context menu button with 3 actions (no icon, just text).`,
        `Long press on the button to show the context menu.`
      ]}
    >
      <ContextMenuButton
        menuConfig={{
          menuTitle: 'ContextMenuButtonSimpleExample01',
          menuItems: [{
            actionKey  : 'key-01',
            actionTitle: 'Action #1',
          }, {
            actionKey  : 'key-02'   ,
            actionTitle: 'Action #2',
          }, {
            actionKey  : 'key-03'   ,
            actionTitle: 'Action #3',
          }],
        }}
        onPressMenuItem={({nativeEvent}) => {
          Alert.alert(
            'onPressMenuItem Event',
            `actionKey: ${nativeEvent.actionKey} - actionTitle: ${nativeEvent.actionTitle}`
          );
        }}
      >
        <ContextMenuCardButton
          buttonTitle={'⭐️ Context Menu Button'}
        />
      </ContextMenuButton>
    </ContextMenuButtonCard>
  );
}
Example #19
Source File: index.tsx    From safetraceapi with GNU General Public License v3.0 5 votes vote down vote up
DataPrivacyScreen = () => {
  const removeDevice = () => {
    from(
      fetch('https://safetraceapi.herokuapp.com/api/devices', {
        method: 'DELETE',
        headers: {
          'Content-Type': 'application/json',
          // api_key: API_KEY,
        },
        body: JSON.stringify({
          // TODO: make device id, row type, infection status dynamic
          device_id: DEVICE_ID,
        }),
      })
    )
      .pipe(
        map((resp: any) => resp.json()),
        tap((resp) => {
          if (typeof resp.error !== 'undefined') {
            console.log(resp.error);
            Alert.alert(
              'Account Deletion Error',
              resp.error,
              [{ text: 'OK', onPress: () => console.log('OK Pressed') }],
              { cancelable: false }
            );
          } else {
            Alert.alert(
              'Successfully Removed Your Device',
              resp.message,
              [{ text: 'OK', onPress: () => console.log('OK Pressed') }],
              { cancelable: false }
            );
          }
        })
      )
      .subscribe();
  };

  return (
    <BaseLayout>
      <Button title="Remove Device" onPress={removeDevice} />
    </BaseLayout>
  );
}
Example #20
Source File: useAlert.ts    From react-native-crypto-wallet-app with MIT License 5 votes vote down vote up
useAlert = () => {
  const alertFunc: AlertFunc = useCallback((title, message, buttons, options) => {
    Alert.alert(title, message, buttons, options);
  }, []);

  return alertFunc;
}
Example #21
Source File: CustomView.tsx    From react-native-paper-onboarding with MIT License 5 votes vote down vote up
CustomView = ({ animatedFocus }: PageContentProps) => {
  //#region animations
  const animatedBoxTranslateY = interpolate(animatedFocus, {
    inputRange: [0, 1],
    outputRange: [100, 0],
    extrapolate: Extrapolate.CLAMP,
  });
  //#endregion

  //#region styles
  const boxStyle = [
    styles.box,
    {
      transform: [
        { translateY: animatedBoxTranslateY },
      ] as Animated.AnimatedTransform,
    },
  ];
  const item1Style = [
    styles.item,
    {
      opacity: interpolate(animatedFocus, {
        inputRange: [0.5, 1],
        outputRange: [0, 1],
        extrapolate: Extrapolate.CLAMP,
      }),
    },
  ];
  const item2Style = [
    styles.item,
    {
      opacity: interpolate(animatedFocus, {
        inputRange: [0.625, 1],
        outputRange: [0, 1],
        extrapolate: Extrapolate.CLAMP,
      }),
    },
  ];
  const item3Style = [
    styles.item2,
    {
      opacity: interpolate(animatedFocus, {
        inputRange: [0.75, 1],
        outputRange: [0, 1],
        extrapolate: Extrapolate.CLAMP,
      }),
    },
  ];
  const buttonStyle = {
    opacity: interpolate(animatedFocus, {
      inputRange: [0.875, 1],
      outputRange: [0, 1],
      extrapolate: Extrapolate.CLAMP,
    }),
  };
  //#endregion

  const handleButtonPress = () => {
    Alert.alert('Button Clicked !');
  };
  return (
    <View
      style={styles.container}
      shouldRasterizeIOS={true}
      needsOffscreenAlphaCompositing={true}
    >
      <Animated.View style={boxStyle} />
      <Animated.View style={item1Style} />
      <Animated.View style={item2Style} />
      <Animated.View style={item3Style} />
      <AnimatedTouchableOpacity style={buttonStyle} onPress={handleButtonPress}>
        <Text style={styles.buttonText}>Button</Text>
      </AnimatedTouchableOpacity>
    </View>
  );
}
Example #22
Source File: Basic.tsx    From react-native-sticky-item with MIT License 5 votes vote down vote up
Basic = () => {
  const flatListRef = useRef<FlatList>(null);

  // styles
  const containerStyle = {
    paddingVertical: SEPARATOR_SIZE * 2,
    backgroundColor: 'white',
  };

  // methods
  const handleStickyItemPress = () => Alert.alert('Sticky Item Pressed');
  const handleScrollToEnd = () => {
    const flatlist = flatListRef.current;
    if (flatlist) {
      flatlist.scrollToEnd({ animated: true });
    }
  };
  const handleScrollToStart = () => {
    const flatlist = flatListRef.current;
    if (flatlist) {
      flatlist.scrollToOffset({ animated: true, offset: 0 });
    }
  };
  const handleScrollToIndex = useCallback(index => {
    const flatlist = flatListRef.current;
    if (flatlist) {
      flatlist.scrollToIndex({ index });
    }
  }, []);

  // render
  const renderItem = ({ index }: ListRenderItemInfo<{}>) => (
    <TouchableOpacity onPress={() => Alert.alert(`Item ${index} Pressed`)}>
      <DummyItem
        index={index}
        borderRadius={BORDER_RADIUS}
        width={STORY_WIDTH}
        height={STORY_HEIGHT}
        backgroundColor={'#dfdfdf'}
      />
    </TouchableOpacity>
  );
  return (
    <SafeAreaView style={styles.root}>
      <View style={containerStyle}>
        <StickyItemFlatList
          ref={flatListRef}
          itemWidth={STORY_WIDTH}
          itemHeight={STORY_HEIGHT}
          separatorSize={SEPARATOR_SIZE}
          borderRadius={BORDER_RADIUS}
          stickyItemWidth={STICKY_ITEM_WIDTH}
          stickyItemHeight={STICKY_ITEM_HEIGHT}
          stickyItemBackgroundColors={['#F8F8FA', '#2d88ff']}
          stickyItemContent={BasicSticky}
          onStickyItemPress={handleStickyItemPress}
          data={data}
          renderItem={renderItem}
        />
      </View>
      <View style={styles.buttons}>
        <Button label="< Scroll To Start" onPress={handleScrollToStart} />
        <Button label="Scroll To End >" onPress={handleScrollToEnd} />
      </View>
      <View style={styles.buttons}>
        <Button label="Scroll To 4" onPress={() => handleScrollToIndex(4)} />
        <Button label="Scroll To 9" onPress={() => handleScrollToIndex(9)} />
        <Button label="Scroll To 14" onPress={() => handleScrollToIndex(14)} />
      </View>
    </SafeAreaView>
  );
}
Example #23
Source File: App.tsx    From rn-credit-card with MIT License 5 votes vote down vote up
App: React.FC = () => {
  let [fontsLoaded] = useFonts({
    RobotoMono_400Regular,
    RobotoMono_700Bold,
  })
  const formMethods = useForm<FormModel>({
    // to trigger the validation on the blur event
    mode: 'onBlur',
    defaultValues: {
      holderName: '',
      cardNumber: '',
      expiration: '',
      cvv: '',
    },
  })
  const { handleSubmit, formState } = formMethods

  function onSubmit(model: FormModel) {
    Alert.alert('Success: ' + JSON.stringify(model, null, 2))
  }

  if (!fontsLoaded) {
    return <AppLoading />
  }

  return (
    <FormProvider {...formMethods}>
      <SafeAreaView style={styles.container}>
        <KeyboardAvoidingView
          style={styles.avoider}
          behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
        >
          <CreditCardForm
            LottieView={LottieView}
            horizontalStart
            overrides={{
              labelText: {
                marginTop: 16,
              },
            }}
          />
        </KeyboardAvoidingView>
        {formState.isValid && (
          <Button
            style={styles.button}
            title={'CONFIRM PAYMENT'}
            onPress={handleSubmit(onSubmit)}
          />
        )}
      </SafeAreaView>
    </FormProvider>
  )
}
Example #24
Source File: FindPw.tsx    From DoobooIAP with MIT License 5 votes vote down vote up
function Page(): ReactElement {
  const [email, setEmail] = useState<string>('');
  const [errorEmail, setErrorEmail] = useState<string>('');
  const [findingPw, setFindingPw] = useState<boolean>(false);

  const { theme } = useThemeContext();

  const onFindPw = async (): Promise<void> => {
    if (!validateEmail(email)) {
      setErrorEmail(getString('EMAIL_FORMAT_NOT_VALID'));
      return;
    }

    setFindingPw(true);
    try {
      await firebase.auth().sendPasswordResetEmail(email);
    } catch (err) {
      Alert.alert(getString('ERROR'), `${err.code}: ${err.message}`);
    } finally {
      Alert.alert(getString('SUCCESS'), getString('EMAIL_PASSWORD_RESET_SENT'));
      setFindingPw(false);
    }
  };

  return (
    <Container>
      <Wrapper>
        <EditText
          testID="input-email"
          errorTestID="error-email"
          textStyle={{
            color: theme.font,
          }}
          borderColor={theme.font}
          focusColor={theme.focused}
          placeholderTextColor={theme.placeholder}
          label={getString('EMAIL')}
          placeholder="[email protected]"
          value={email}
          onChangeText={(text: string): void => {
            setEmail(text);
            setErrorEmail('');
          }}
          style={{ marginTop: 20 }}
          errorText={errorEmail}
          onSubmitEditing={onFindPw}
        />
        <ButtonWrapper>
          <Button
            testID="btn-find-pw"
            isLoading={findingPw}
            onPress={onFindPw}
            containerStyle={{ height: 52, backgroundColor: theme.primary }}
            textStyle={{ color: theme.fontInverse, fontWeight: 'bold' }}
            text={getString('FIND_PW')}
          />
        </ButtonWrapper>
      </Wrapper>
    </Container>
  );
}
Example #25
Source File: App.tsx    From react-native-cn-quill with MIT License 5 votes vote down vote up
handleGetHtml = () => {
    this._editor.current?.getHtml().then((res) => {
      console.log('Html :', res);
      Alert.alert(res);
    });
  };
Example #26
Source File: SyncManager.ts    From solid-health with MIT License 5 votes vote down vote up
onWebIdChange(async (webId) => {
  profile = null;
  observationLocation = null;
  fitnessData.loading = true;
  fitnessData.heartRate = [];
  fitnessData.steps = [];
  fitnessData.distance = [];
  syncEvents.emit('fitnessData', fitnessData.loading);

  if (webId == null) {
    fitnessData.loading = false;
    syncEvents.emit('profile', profile);
    return;
  }

  let success = false;

  try {
    const store = rdf.graph();
    const fetcher = new rdf.Fetcher(store, { fetch: authenticatedFetch });

    setSyncStatus('Loading profile');

    profile = await fetchProfile(store, fetcher, webId);
    syncEvents.emit('profile', profile);

    if (!profile.privateTypeIndex) {
      throw new Error('No private type index');
    }

    setSyncStatus('Loading private type index');

    observationLocation = await fetchTypeIndex(store, fetcher, webId, profile.privateTypeIndex);
    
    setSyncStatus('Loading data from pod');

    await fetchObservations(store, fetcher, webId, observationLocation);

    success = true;
    setSyncStatus('Done', 1, 1);

  } catch (err) {
    console.warn(err);
    setSyncStatus('Could not load profile', 0, 1);
    Alert.alert('Could not load profile', err.toString());
  }

  fitnessData.loading = false;
  syncEvents.emit('fitnessData', fitnessData.loading);

  if (success) {
    const end = moment.utc().endOf('month');
    const start = end.clone().startOf('month');
    syncData(start, end);
  }
});
Example #27
Source File: ErrorReportingAlert.ts    From jellyfin-audio-player with MIT License 5 votes vote down vote up
/**
 * This will send out an alert message asking the user if they want to enable
 * error reporting.
 */
export default function ErrorReportingAlert() {
    const { hasReceivedErrorReportingAlert } = useTypedSelector(state => state.settings);
    const navigation = useNavigation<ModalNavigationProp>();
    const dispatch = useAppDispatch();

    useEffect(() => {
        // Only send out alert if we haven't done so ever
        if (!hasReceivedErrorReportingAlert) {
            // Generate the alert
            Alert.alert(
                t('enable-error-reporting'),
                t('enable-error-reporting-description'),
                [
                    {
                        text: t('enable'),
                        style: 'default',
                        onPress: () => {
                            setSentryStatus(true);
                        }
                    },
                    {
                        text: t('disable'),
                        style: 'destructive',
                        onPress: () => {
                            setSentryStatus(false);
                        }
                    },
                    {
                        text: t('more-info'),
                        style: 'cancel',
                        onPress: () => {
                            navigation.navigate('ErrorReporting');
                        }
                    }
                ]
            );

            // Store the flag that we have sent out the alert, so that we don't
            // have to do so anymore in the future.
            dispatch(setReceivedErrorReportingAlert());
        }
        
    }, [dispatch, hasReceivedErrorReportingAlert, navigation]);

    return null;
}
Example #28
Source File: errorHandler.ts    From lexicon with MIT License 5 votes vote down vote up
export function errorHandlerAlert(
  error: ApolloError | string,
  navigate?: Function,
  isFiltered = false,
) {
  let errorMsg;

  if (typeof error === 'string') {
    errorMsg = error;
  } else {
    errorMsg = errorHandler(error, isFiltered, false);
  }

  let errorMsgi8n = t('{errorMsg}', { errorMsg });

  switch (errorMsg) {
    case LoginError:
      Alert.alert(t('Please Log In'), errorMsgi8n, [
        { text: t('Close') },
        {
          text: t('Log In'),
          onPress: () => (navigate ? navigate('Login') : undefined),
        },
      ]);
      break;
    case UsedTitleError:
      Alert.alert(
        t('Title Already Exists'),
        t(
          'A Post with this title has already been created. Please use a different title.',
        ),
        [{ text: t('Got it') }],
      );
      break;
    case EditPostError:
      Alert.alert(t('Unable to Edit'), errorMsgi8n, [{ text: t('Got it') }]);
      break;
    case ChangeUsernameError:
      Alert.alert(t('Username Unavailable'), errorMsgi8n, [
        { text: t('Got it') },
      ]);
      break;
    default:
      Alert.alert(t('Error'), errorMsgi8n, [{ text: t('Got it') }]);
  }
}
Example #29
Source File: ClientListItem.tsx    From react-native-network-client with Apache License 2.0 5 votes vote down vote up
ClientListItem = (props: ClientListItemProps) => {
    const {
        index,
        deleteClient,
        item: { name, client, type },
    } = props;

    const viewClient = () => {
        let screen = "GenericClientRequest";
        if (type === ClientType.API) {
            screen = "APIClient";
        } else if (type === ClientType.WEBSOCKET) {
            screen = "WebSocketClient";
        }

        props.navigate(screen, { item: props.item });
    };

    const invalidateClient = () => {
        if ("invalidate" in client) {
            client.invalidate();
            deleteClient(index);
        }
    };

    const removeClient = () => {
        "invalidate" in client &&
            Alert.alert(
                "Remove Client",
                "",
                [{ text: "Cancel" }, { text: "OK", onPress: invalidateClient }],
                { cancelable: true }
            );
    };

    const Subtitle = () => {
        if ("baseUrl" in client) {
            return (
                <ListItem.Subtitle testID="client_list_item.subtitle">
                    {client.baseUrl}
                </ListItem.Subtitle>
            );
        } else if ("url" in client) {
            return (
                <ListItem.Subtitle testID="client_list_item.subtitle">
                    {client.url}
                </ListItem.Subtitle>
            );
        }

        return null;
    };

    return (
        <ListItem
            onPress={viewClient}
            onLongPress={removeClient}
            bottomDivider
            testID="client_list_item.item"
        >
            <ListItem.Content testID="client_list_item.content">
                <ListItem.Title testID="client_list_item.title">
                    {name}
                </ListItem.Title>
                <Subtitle />
            </ListItem.Content>
            <ListItem.Chevron testID="client_list_item.chevron" />
        </ListItem>
    );
}