0

I need to navigate to an authenticate screen after checking the login fields in a login() function.If API request respond is valid then navigation should be done and if not keep staying in the login screen.

Here is my login() function,

>  loginUser = () =>{
>         this.setState({loading:true})
>         const user = {
>            email:this.state.email,
>            password:this.state.password
>        }
>        Axios
>          .post('http://10.0.2.2:5000/users/login',user)
>          .then(res=>{
>             if(res.status === 200){
>                 deviceStorage.saveItem('id',res.data.id);
>                 deviceStorage.saveItem("jwtToken", res.data.token);
>                 Alert.alert('Successfuly loged in')

>                 this.props.navigation.navigate('AuthHome')
>             }
>             this.setState({loading:false})
>          })
>          .catch(err=>{
>              if(err.response.status ===400){
>                  Alert.alert("Incorrect Email or Password");
>              }
>              this.setState({loading:false})
>          })
>     }

But I only can navigate When I put navigation in onPress button.

                const {navigate} = this.props.navigation
                <TouchableOpacity
                    onPress={()=>navigate('AuthHome',{screenname:'Authe'})}
                   // onPress={()=>this.loginUser}
                >
                    <Text> Log In </Text>
                </TouchableOpacity>
                <Text  
                   onPress={()=>navigation.navigate('Signup')}
                >
                    Don't have account? Click here to Sign Up
                </Text> 

But what I want is to trigger login function when user press the Login button.Then login function will check text fields and navigate to appropriate screens.

onPress={()=>this.login}

I tried using this.props.navigation.navigate('screen name') inside login function but nothing happens.It's look like I can't use this.props.navigation.navigate('screen name') inside axios.

What are the changes I should do? Can anyone help me with this.

Kavishka Gamage
  • 102
  • 2
  • 10

1 Answers1

0

This occurs because this does not exists inside axios .then() scope. More detailed info can be found here: How to access the correct `this` inside a callback?

The majority consense about tells to transform this into a variable:

const _this = this;

And, in your case call this way inside axios .then() scope:

_this.props.navigation.navigate('AuthHome')
  • This is not the cause for my situation. It was a mistake done by me when trying to access nested navigator. After fixing it "this" is accessible inside axio. – Kavishka Gamage Jun 26 '20 at 18:41