Ad

Fix An Unhandled Promise Rejection In React Native

I am trying to go to a new screen using react navigation but am running into a warning [Unhandled promise rejection: TypeError: undefined is not an object (evaluating 'this.navigation.navigate')]. No error is thrown (it is only a warning) but the app does not move to the next screen.

I have tried unsuccessfully to call a separate function holding the navigation code, and used an arrow function, but neither options worked.

Here is my code...

import React from 'react';
import {
  StyleSheet,
  View,
  TextInput,
  AlertIOS,
} from 'react-native';

import { withNavigation } from 'react-navigation';

import database from '../Database.js';

const db = new database();


class LoginForm extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <View style={styles.container}>
        <TextInput
          placeholder="Access Code"
          returnKeyType="go"
          onSubmitEditing={text => {
            db.isValidCode(text.nativeEvent.text).then(isValid => {
              if (isValid) {
                this.navigation.navigate('Create')// this throws warning
              } else {
                AlertIOS.alert(
                  "We're Sorry...",
                  'The code you entered was not found in the database! Please contact support for further assistance.'
                );
              }
            }).catch(function(error) {
              console.log(error);
              throw error;
            }) // this "catch" statement didn't fix the warning
          }}
        />
      </View>
    );
  }
}

export default withNavigation(LoginForm);

And the database file...

var firebase = require('firebase');

if (!firebase.apps.length) {
    firebase.initializeApp({
        apiKey: "key",
        authDomain: "domain",
        databaseURL: "url",
        storageBucket: "bucket",
    });
}

class Database {
    constructor() {
      this.codesRef = firebase.database().ref('codes');
    }

    async isValidCode(text) {
      let codeIsFound = false;
      let identifier = "";
      let db_snapshot = await this.codesRef.once('value');
       db_snapshot.forEach(code_snapshot => {
           if (text == code_snapshot.val().value) {
              codeIsFound = true;
              identifier = code_snapshot.key;
            }
       });
       return codeIsFound; 
    };

}

module.exports = Database;

I am not sure why the navigation isn't working. Everything worked fine and was much simpler when the function was in the same file that it was being used in. Any help / pointers are appreciated!

Ad

Answer

You need to use:

this.props.navigation.navigate('Create')

instead of:

this.navigation.navigate('Create')

because withNavigation adds navigation to your component's properties not to the component itself.

Ad
source: stackoverflow.com
Ad