Ad

Undefined Is Not An Object (evaluating 'this.props.navigation') With Fetch

I try my best to make a Sign-in form with React native but :

  • I can't make a redirection to 'App', the error message is : (TypeError: undefined is not an object (evaluating 'this.props.navigation')])

    try {
      fetch('http://93.xxx.xx.xx:5151/login', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
          },
          body: formBody,
        })
        .then(function(response) {
          if (response.ok) {
            this.props.navigation.navigate('App');
          } else {
            throw new Error("Failed to fetch [error : " + response.status + "]");
            Alert.alert("Error [" + response.status + "] - " + response.statusText);
          }
        })
        .then(function(response) {
          if (response.ok) {
            Alert.alert(response.userToken);
            console.log(response);
          } else {
            Alert.alert("Error [" + response.status + "] - " + response.statusText);
          }
        })
    } catch (error) {
      if (error) {
        console.error(error);
      }
    }
    

Is anyone know how to do that ?

  • I only have one solution so far :

    fetch('http://93.xxx.xx.xx:5151/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
        },
        body: formBody
      })
      .then(res => {
        if (res.ok) {
          this.props.navigation.navigate('App')
        } else {
          if (res.status == 400) {
            Alert.alert("Error 400 : login rejected because -> " + res.message)
          } else {
            throw Error(`Request rejected with status ${res.status}`);
          }
        }
      })
      .catch(console.error)
    }
    

But with this solution i don't know how to save the User token ...

Ad

Answer

Its a scoping issue , change this :

.then(function(response) { // due to this you are losing `this` scope inside it

// due to that, this is not accessible, in result you will get error
this.props.navigation.navigate('App');  

To :

.then((response) => { // <--- Fat arrow is what you need
Ad
source: stackoverflow.com
Ad