Home > Blockchain >  getting the following warning while trying to run my app: Possible Unhandled Promise Rejection (id:1
getting the following warning while trying to run my app: Possible Unhandled Promise Rejection (id:1

Time:01-16

I'm currently working on an app and I'm getting this warning and wanted to know what I could do to fix the promise rejection. This warning appears as soon as the screen mounts.

The screenshot of the error:

enter image description here

Code for app.js:

import React, { useState } from "react";
import { NavigationContainer } from "@react-navigation/native";
import { createStackNavigator } from "@react-navigation/stack";
import { View, Text, TouchableOpacity, Alert } from "react-native";

import Main from "./Screens/Main";
import Login from "./Screens/Login";
import Settings from "./Screens/Settings";
import EditPatient from "./Screens/EditPatient";
import Add from "./Screens/Add";
import * as firebase from "firebase/auth";
import { Input } from "react-native-elements";
import theme from "./Props/theme";
import './Config/Firebase'
import * as Font from "expo-font";
import ViewSelectedTeeth from "./Screens/ViewSelectedTeeth";
import Pending from "./Screens/Pending";
import Completed from "./Screens/Completed";
import AllCases from "./Screens/AllCases";
import { LogBox } from "react-native";

const Stack = createStackNavigator();

export default class App extends React.Component {
  async componentDidMount() {
    await Font.loadAsync({
      ubuntuMedium: require("./Assets/Fonts/Ubuntu-Medium.ttf"),
      ubuntuBold: require("./Assets/Fonts/Ubuntu-Bold.ttf"),
      ubuntuItalic: require("./Assets/Fonts/Ubuntu-Italic.ttf"),
      ubuntuLight: require("./Assets/Fonts/Ubuntu-Light.ttf"),
      ubuntuRegular: require("./Assets/Fonts/Ubuntu-Regular.ttf"),
      dosisMedium: require("./Assets/Fonts/Dosis-Medium.ttf"),
      dosisBold: require("./Assets/Fonts/Dosis-Bold.ttf"),
      dosisSemibold: require("./Assets/Fonts/Dosis-SemiBold.ttf"),
      dosisLight: require("./Assets/Fonts/Dosis-Light.ttf"),
      dosisRegular: require("./Assets/Fonts/Dosis-Regular.ttf"),
      comfortaaMedium: require("./Assets/Fonts/Comfortaa-Medium.ttf"),
      comfortaaBold: require("./Assets/Fonts/Comfortaa-Bold.ttf"),
      comfortaaSemibold: require("./Assets/Fonts/Comfortaa-SemiBold.ttf"),
      comfortaaLight: require("./Assets/Fonts/Comfortaa-Light.ttf"),
      comfortaaRegular: require("./Assets/Fonts/Comfortaa-Regular.ttf"),
    });
    LogBox.ignoreLogs(["Setting a timer for a long period of time"]);
  }

  state = {
    currentPassword: "",
    newPassword: "",
    isFirstLaunch: null,
  };

  resetPassword = ({ navigation }) => {
    const [currentPassword, setCurrentPassword] = useState("");
    const [newPassword, setNewPassword] = useState("");
    const reauthenticate = (currentPassword) => {
      var user = firebase().currentUser;
      var cred = firebase.EmailAuthProvider.credential(
        user.email,
        currentPassword
      );
      return user.reauthenticateWithCredential(cred);
    };
    const onChangePassword = async () => {
      await reauthenticate(currentPassword)
        .then(() => {
          var user = firebase().currentUser;
          user
            .updatePassword(newPassword)
            .then(() => {
              Alert.alert("Password has been changed");
              setCurrentPassword("");
              setNewPassword("");
              navigation.navigate("Settings");
            })
            .catch((error) => {
              Alert.alert(error.message);
            });
        })
        .catch((error) => {
          Alert.alert(error.message);
        });
    };

    return (
      <View style={{ flex: 1, justifyContent: "center", marginHorizontal: 25 }}>
        <Input
          placeholder="Current Password"
          value={currentPassword}
          onChangeText={(currentPassword) =>
            setCurrentPassword(currentPassword)
          }
          secureTextEntry
        />
        <Input
          placeholder="New Password"
          value={newPassword}
          onChangeText={(newPassword) => setNewPassword(newPassword)}
          secureTextEntry
        />

        <TouchableOpacity
          onPress={() => onChangePassword()}
          style={{
            paddingVertical: 20,
            alignItems: "center",
            justifyContent: "center",
            backgroundColor: theme.darkBlue,
            borderRadius: 40,
          }}
        >
          <Text
            style={{ fontSize: 20, color: "white", fontFamily: "ubuntuBold" }}
          >
            Change Password
          </Text>
        </TouchableOpacity>
      </View>
    );
  };

  render() {
    return (
      <NavigationContainer>
        <Stack.Navigator
          screenOptions={{
            gestureEnabled: true,
            gestureDirection: "horizontal",
            headerBackTitle: "Back",
            headerBackTitleStyle: { color: "black" },
            headerTintColor: "black",
            headerMode:"screen"
          }}
          
        >
          <Stack.Screen
            name="Login"
            component={Login}
            options={{ headerShown: false }}
          />
          <Stack.Screen
            name="Home"
            component={Main}
            options={{ headerShown: false }}
          />
          <Stack.Screen
            name="Settings"
            component={Settings}
            options={{ headerShown: true }}
          />
          <Stack.Screen
            name="Edit"
            component={EditPatient}
            options={{ headerShown: false }}
          />
          <Stack.Screen
            name="Add"
            component={Add}
            options={{ headerShown: true }}
          />

          <Stack.Screen
            name="Reset Password"
            component={this.resetPassword}
            options={{ headerShown: true }}
          />

          <Stack.Screen
            name="View Selected Teeth"
            component={ViewSelectedTeeth}
            options={{ headerShown: false }}
          />

          <Stack.Screen
            name="Remaining Cases"
            component={Pending}
            options={{ headerShown: true }}
          />

          <Stack.Screen
            name="Completed Cases"
            component={Completed}
            options={{ headerShown: true }}
          />

          <Stack.Screen
            name="All Cases"
            component={AllCases}
            options={{ headerShown: true }}
          />
        </Stack.Navigator>
      </NavigationContainer>
    );
  }
}

Code for login.js (as it is the first screen on my stack...I think there may be an issue in that code) :

import React from "react";
import {
  View,
  Text,
  TextInput,
  ActivityIndicator,
  Modal,
  ScrollView,
  TouchableOpacity,
  StyleSheet,
  Image,
  KeyboardAvoidingView,
  Alert,
  StatusBar,
  Platform,
} from "react-native";
import { CheckBox, Input } from "react-native-elements";
import {signInWithEmailAndPassword, createUserWithEmailAndPassword} from "firebase/auth";
import * as db from 'firebase/firestore'
import Constants from "expo-constants";

export default class Login extends React.Component {
  state = {
    email: "",
    password: "",
    showPassword: false,
    userLoggedIn: false,
    modalEmail: "",
    modalPassword: "",
    username: "",
    clinicName: "",
    age: "",
    isModalVisible: false,
    confirmPassword: "",
  };

  showModal = () => {
    return (
      <Modal
        visible={this.state.isModalVisible}
        transparent={false}
        animationType="fade"
      >
        <Text style={styles.signUpText}>Sign up to get started</Text>

        <ScrollView style={{ marginTop: 20 }}>
          <TextInput
            style={styles.formTextInput}
            placeholder={"Userame"}
            value={this.state.username}
            maxLength={40}
            placeholderTextColor="gray"
            onChangeText={(text) => {
              this.setState({
                username: text,
              });
            }}
          />

          <TextInput
            style={styles.formTextInput}
            placeholderTextColor="gray"
            placeholder={"Email ID"}
            value={this.state.modalEmail}
            onChangeText={(text) => {
              this.setState({
                modalEmail: text,
              });
            }}
            keyboardType="email-address"
            autoCapitalize="none"
          />
          <TextInput
            style={styles.formTextInput}
            placeholderTextColor="gray"
            placeholder="Clinic name"
            maxLength={40}
            value={this.state.clinicName}
            onChangeText={(text) => {
              this.setState({
                clinicName: text,
              });
            }}
          />
          <TextInput
            style={styles.formTextInput}
            placeholderTextColor="gray"
            placeholder="Age"
            maxLength={2}
            value={this.state.age}
            onChangeText={(text) => {
              this.setState({
                age: text,
              });
            }}
          />
          <TextInput
            style={styles.formTextInput}
            placeholderTextColor="gray"
            placeholder="Phone number"
            maxLength={10}
            value={this.state.phoneNumber}
            onChangeText={(text) => {
              this.setState({
                phoneNumber: text,
              });
            }}
            keyboardType="numeric"
          />

          <TextInput
            style={styles.formTextInput}
            placeholderTextColor="gray"
            placeholder={"Password"}
            secureTextEntry={true}
            value={this.state.modalPassword}
            onChangeText={(text) => {
              this.setState({
                modalPassword: text,
              });
            }}
          />

          <TextInput
            style={styles.formTextInput}
            placeholderTextColor="gray"
            placeholder={"Confirm Password"}
            secureTextEntry={true}
            value={this.state.confirmPassword}
            onChangeText={(text) => {
              this.setState({
                confirmPassword: text,
              });
            }}
          />

          <TouchableOpacity
            style={styles.registerButton}
            onPress={() => {
              if (
                this.state.modalEmail === "" ||
                this.state.username === "" ||
                this.state.clinicName === "" ||
                this.state.age === "" ||
                this.state.phoneNumber === "" ||
                this.state.modalPassword === "" ||
                this.state.confirmPassword === ""
              ) {
                Alert.alert(
                  "Couldn't sign up",
                  "Please enter all information to sign up"
                );
              } else if (
                this.state.modalPassword !== this.state.confirmPassword
              ) {
                Alert.alert(
                  "Couldn't sign up",
                  "Please make sure the password and confirm password match"
                );
              } else {
                this.onSignUp(this.state.modalEmail, this.state.modalPassword);
              }
            }}
          >
            <Text> Register </Text>
          </TouchableOpacity>

          <TouchableOpacity
            style={styles.cancelButton}
            onPress={() => this.setState({ isModalVisible: false })}
          >
            <Text>Cancel</Text>
          </TouchableOpacity>
        </ScrollView>
      </Modal>
    );
  };

  onSignIn = async (email, password) => {
    this.setState({ userLoggedIn: true });
    signInWithEmailAndPassword(email, password)
      .then((response) => {
        this.props.navigation.replace("Home");
      })
      .catch((error) => {
        Alert.alert("Couldn't sign in", error.message);
      });
    this.setState({ userLoggedIn: false });
  };

  onSignUp = async (email, password) => {
    createUserWithEmailAndPassword(
        this.state.modalEmail,
        this.state.modalPassword
      )
      .then(() => {
        db.addDoc("Users",{
            username: this.state.username,
            email_id: this.state.modalEmail,
            clinicName: this.state.clinicName,
            age: this.state.age,
            phoneNumber: this.state.phoneNumber,
            tablets: []
        })
        this.setState({ isModalVisible: false });
        this.props.navigation.replace("Home");
      })
      .catch((error) => {
        Alert.alert("Coudn't create user", error.message);
        console.warn(error)
      });
  };

  render() {
    return (
      <KeyboardAvoidingView style={{ flex: 1, backgroundColor: "#dfff" }}>
        {this.showModal()}
        <StatusBar hidden />
        <Image
          source={require("../Assets/Images/dentist.png")}
          style={{
            width: 150,
            height: 150,
            alignSelf: "center",
            marginTop: 45,
          }}
        />

        <View style={{ marginTop: 20, marginHorizontal: 20 }}>
          <Text style={{ textTransform: "uppercase", color: "#646464" }}>
            email id
          </Text>
          <Input
            style={{
              marginHorizontal: 10,
              paddingTop: 10,
              paddingHorizontal: 10,
              marginBottom: 10,
              marginVertical: 5,
              color: "#646464",
              paddingBottom: 4,
            }}
            value={this.state.email}
            keyboardType="email-address"
            autoCompleteType="email"
            autoCapitalize="none"
            onChangeText={(email) => this.setState({ email: email })}
          />
          <Text style={{ textTransform: "uppercase", color: "#646464" }}>
            password
          </Text>
          <Input
            style={{
              marginHorizontal: 10,
              paddingTop: 10,
              paddingHorizontal: 10,
              marginBottom: 10,
              marginVertical: 5,
              color: "#646464",
              paddingBottom: 4,
            }}
            value={this.state.password}
            keyboardType="visible-password"
            onChangeText={(password) => this.setState({ password: password })}
            secureTextEntry={this.state.showPassword ? false : true}
          />
          {Platform.OS === "ios" ? (
            <CheckBox
              checkedColor="#0F0"
              onPress={() =>
                this.setState({
                  showPassword: !this.state.showPassword,
                })
              }
              size={20}
              title="Show password"
              uncheckedColor="#F00"
              checked={this.state.showPassword}
              checkedIcon="check"
              uncheckedIcon="close"
            />
          ) : null}
          <TouchableOpacity
            style={{
              alignItems: "center",
              padding: 15,
              backgroundColor: "#FFCBF6",
              marginVertical: 15,
              borderRadius: 30,
            }}
            onPress={() => this.onSignIn(this.state.email, this.state.password)}
          >
            {this.state.userLoggedIn === false ? (
              <Text
                style={{
                  fontSize: 20,
                  color: "#494949",
                  fontWeight: "bold",
                  textTransform: "uppercase",
                }}
              >
                Sign in
              </Text>
            ) : (
              <ActivityIndicator size={"large"} />
            )}
          </TouchableOpacity>
          <TouchableOpacity
            style={{
              alignItems: "center",
              padding: 15,
              backgroundColor: "#D1CCFF",
              marginBottom: 15,
              borderRadius: 30,
            }}
            onPress={() => this.setState({ isModalVisible: true })}
          >
            <Text
              style={{
                fontSize: 20,
                color: "#494949",
                fontWeight: "bold",
                textTransform: "uppercase",
              }}
            >
              Sign up
            </Text>
          </TouchableOpacity>
        </View>
      </KeyboardAvoidingView>
    );
  }
}

const styles = StyleSheet.create({
  formTextInput: {
    width: "75%",
    height: 35,
    alignSelf: "center",
    borderColor: "#8022d9",
    borderRadius: 10,
    borderWidth: 1,
    marginTop: 20,
    padding: 10,
  },
  cancelButton: {
    width: 200,
    height: 30,
    justifyContent: "center",
    alignItems: "center",
    marginTop: 5,
    alignSelf: "center",
  },
  registerButton: {
    width: 200,
    height: 40,
    alignItems: "center",
    justifyContent: "center",
    borderWidth: 1,
    borderRadius: 10,
    marginTop: 30,
    alignSelf: "center",
  },
  signUpText: {
    alignSelf: "center",
    marginTop: 50,
    fontSize: 30,
    fontWeight: "bold",
  },
  linearGradient: {
    flex: 1,
    paddingLeft: 15,
    paddingRight: 15,
    borderRadius: 5,
  },
  buttonText: {
    fontSize: 18,
    textAlign: "center",
    margin: 10,
    color: "#ffffff",
    backgroundColor: "transparent",
  },
});

If you have any idea on how to fix this please let me know. Thanks in advance!

CodePudding user response:

I don't see anywhere checking if the Fonts are loaded!

Check the changes where you see //ADD THIS HERE !!!:

From the docs

app.js

import React, { useState } from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import { View, Text, TouchableOpacity, Alert } from 'react-native';

import Main from './Screens/Main';
import Login from './Screens/Login';
import Settings from './Screens/Settings';
import EditPatient from './Screens/EditPatient';
import Add from './Screens/Add';
import * as firebase from 'firebase/auth';
import { Input } from 'react-native-elements';
import theme from './Props/theme';
import './Config/Firebase';
import * as Font from 'expo-font';
import ViewSelectedTeeth from './Screens/ViewSelectedTeeth';
import Pending from './Screens/Pending';
import Completed from './Screens/Completed';
import AllCases from './Screens/AllCases';
import { LogBox } from 'react-native';

const Stack = createStackNavigator();

export default class App extends React.Component {
  async componentDidMount() {
    await Font.loadAsync({
      ubuntuMedium: require('./Assets/Fonts/Ubuntu-Medium.ttf'),
      ubuntuBold: require('./Assets/Fonts/Ubuntu-Bold.ttf'),
      ubuntuItalic: require('./Assets/Fonts/Ubuntu-Italic.ttf'),
      ubuntuLight: require('./Assets/Fonts/Ubuntu-Light.ttf'),
      ubuntuRegular: require('./Assets/Fonts/Ubuntu-Regular.ttf'),
      dosisMedium: require('./Assets/Fonts/Dosis-Medium.ttf'),
      dosisBold: require('./Assets/Fonts/Dosis-Bold.ttf'),
      dosisSemibold: require('./Assets/Fonts/Dosis-SemiBold.ttf'),
      dosisLight: require('./Assets/Fonts/Dosis-Light.ttf'),
      dosisRegular: require('./Assets/Fonts/Dosis-Regular.ttf'),
      comfortaaMedium: require('./Assets/Fonts/Comfortaa-Medium.ttf'),
      comfortaaBold: require('./Assets/Fonts/Comfortaa-Bold.ttf'),
      comfortaaSemibold: require('./Assets/Fonts/Comfortaa-SemiBold.ttf'),
      comfortaaLight: require('./Assets/Fonts/Comfortaa-Light.ttf'),
      comfortaaRegular: require('./Assets/Fonts/Comfortaa-Regular.ttf'),
    });
    LogBox.ignoreLogs(['Setting a timer for a long period of time']);
    this.setState({ fontsLoaded: true }); // ADD THIS HERE !!!
  }

  state = {
    currentPassword: '',
    newPassword: '',
    isFirstLaunch: null,
    fontsLoaded: false, // THIS HERE !!!
  };

  resetPassword = ({ navigation }) => {
    const [currentPassword, setCurrentPassword] = useState('');
    const [newPassword, setNewPassword] = useState('');
    const reauthenticate = (currentPassword) => {
      var user = firebase().currentUser;
      var cred = firebase.EmailAuthProvider.credential(
        user.email,
        currentPassword,
      );
      return user.reauthenticateWithCredential(cred);
    };
    const onChangePassword = async () => {
      await reauthenticate(currentPassword)
        .then(() => {
          var user = firebase().currentUser;
          user
            .updatePassword(newPassword)
            .then(() => {
              Alert.alert('Password has been changed');
              setCurrentPassword('');
              setNewPassword('');
              navigation.navigate('Settings');
            })
            .catch((error) => {
              Alert.alert(error.message);
            });
        })
        .catch((error) => {
          Alert.alert(error.message);
        });
    };

    return (
      <View style={{ flex: 1, justifyContent: 'center', marginHorizontal: 25 }}>
        <Input
          placeholder="Current Password"
          value={currentPassword}
          onChangeText={(currentPassword) =>
            setCurrentPassword(currentPassword)
          }
          secureTextEntry
        />
        <Input
          placeholder="New Password"
          value={newPassword}
          onChangeText={(newPassword) => setNewPassword(newPassword)}
          secureTextEntry
        />

        <TouchableOpacity
          onPress={() => onChangePassword()}
          style={{
            paddingVertical: 20,
            alignItems: 'center',
            justifyContent: 'center',
            backgroundColor: theme.darkBlue,
            borderRadius: 40,
          }}
        >
          <Text
            style={{ fontSize: 20, color: 'white', fontFamily: 'ubuntuBold' }}
          >
            Change Password
          </Text>
        </TouchableOpacity>
      </View>
    );
  };

  render() {
    // THIS HERE !!!
    // Use the font with the fontFamily property after loading
    if (this.state.fontsLoaded) {
      return (
        <NavigationContainer>
          <Stack.Navigator
            screenOptions={{
              gestureEnabled: true,
              gestureDirection: 'horizontal',
              headerBackTitle: 'Back',
              headerBackTitleStyle: { color: 'black' },
              headerTintColor: 'black',
              headerMode: 'screen',
            }}
          >
            <Stack.Screen
              name="Login"
              component={Login}
              options={{ headerShown: false }}
            />
            <Stack.Screen
              name="Home"
              component={Main}
              options={{ headerShown: false }}
            />
            <Stack.Screen
              name="Settings"
              component={Settings}
              options={{ headerShown: true }}
            />
            <Stack.Screen
              name="Edit"
              component={EditPatient}
              options={{ headerShown: false }}
            />
            <Stack.Screen
              name="Add"
              component={Add}
              options={{ headerShown: true }}
            />

            <Stack.Screen
              name="Reset Password"
              component={this.resetPassword}
              options={{ headerShown: true }}
            />

            <Stack.Screen
              name="View Selected Teeth"
              component={ViewSelectedTeeth}
              options={{ headerShown: false }}
            />

            <Stack.Screen
              name="Remaining Cases"
              component={Pending}
              options={{ headerShown: true }}
            />

            <Stack.Screen
              name="Completed Cases"
              component={Completed}
              options={{ headerShown: true }}
            />

            <Stack.Screen
              name="All Cases"
              component={AllCases}
              options={{ headerShown: true }}
            />
          </Stack.Navigator>
        </NavigationContainer>
      );
      // THIS HERE !!!
    } else {
      return null;
    }
  }
}


CodePudding user response:

The warning appears since you did not prefer using try(){}catch(err){} block for await Font.loadAsync(){}. If you check the documentation on using this function on using try catch for font.loadAsync(), it allows you to use try catch block. So if you want to remove the warning message just use following code:

  async componentDidMount() {
   try{
    await Font.loadAsync({
      ubuntuMedium: require("./Assets/Fonts/Ubuntu-Medium.ttf"),
      ubuntuBold: require("./Assets/Fonts/Ubuntu-Bold.ttf"),
      ubuntuItalic: require("./Assets/Fonts/Ubuntu-Italic.ttf"),
      ubuntuLight: require("./Assets/Fonts/Ubuntu-Light.ttf"),
      ubuntuRegular: require("./Assets/Fonts/Ubuntu-Regular.ttf"),
      dosisMedium: require("./Assets/Fonts/Dosis-Medium.ttf"),
      dosisBold: require("./Assets/Fonts/Dosis-Bold.ttf"),
      dosisSemibold: require("./Assets/Fonts/Dosis-SemiBold.ttf"),
      dosisLight: require("./Assets/Fonts/Dosis-Light.ttf"),
      dosisRegular: require("./Assets/Fonts/Dosis-Regular.ttf"),
      comfortaaMedium: require("./Assets/Fonts/Comfortaa-Medium.ttf"),
      comfortaaBold: require("./Assets/Fonts/Comfortaa-Bold.ttf"),
      comfortaaSemibold: require("./Assets/Fonts/Comfortaa-SemiBold.ttf"),
      comfortaaLight: require("./Assets/Fonts/Comfortaa-Light.ttf"),
      comfortaaRegular: require("./Assets/Fonts/Comfortaa-Regular.ttf"),
    });
    LogBox.ignoreLogs(["Setting a timer for a long period of time"]);
   }catch(error){
     // Do something with the error
   }
  }
  •  Tags:  
  • Related