Reputation: 49
I'm trying to create a login screen with react-native. My problem is that pressing Login button doesn't navigate to correct screen without reloading the test device. This means that I'm getting correct auth tokens from api, but the navigation doesnt't work. What am I doing wrong?
Here is my login page:
import React, {Component} from 'react';
import {Platform, StyleSheet, TextInput, Button, View, AsyncStorage, Alert} from 'react-native';
import axios from 'axios';
//import Loading from '../common/Loading'
//import Navigation from '../common/navigation'
import { onSignIn, STORAGE_KEY } from '../common/auth';
import Logout from './logout.js'
import {createStackNavigator, createAppContainer } from "react-navigation";
import SignedIn from '../navigation/SignedIn.js'
import logout from './logout.js'
export default class login extends Component {
constructor(props){
super(props);
this.state = {
email: '',
password: '',
};
}
// funktio joka hoitaa apikutsun eli hakee apista tokenin joka vahvistaa kirjautumisen.
loginUser() {
const { email, password,} = this.state;
//tähän myöhemmin virheiden käsittely
return axios.post("https://*******.com/auth",{
email: email,
password: password
})
// apista saatu token annetaan arvoksi STORAGE_KEY:lle
.then((response) => {
return onSignIn(STORAGE_KEY, response.token);
})
}
render() {
const { navigate } = this.props.navigation;
return (
<View>
<TextInput
style={styles.input}
onChangeText={(text) => this.setState({email: text})}
placeholder="E-Mail"
/>
<TextInput
style={styles.input}
onChangeText={(text) => this.setState({password:text})}
secureTextEntry={true}
placeholder="Password"
/>
<Button onPress={() => {
this.loginUser().then(() => navigate('SignedIn'));
}}
style={styles.button}
title="Login">
</Button>
</View>
)};
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F5FCFF',
},
});
Upvotes: 0
Views: 265
Reputation: 739
Try doing following in login function, pass navigation
in login function while calling it from onPress
.
loginUser(navigation) {
const { email, password,} = this.state;
//tähän myöhemmin virheiden käsittely
axios.post("https://*******.com/auth",{
email: email,
password: password
})
// apista saatu token annetaan arvoksi STORAGE_KEY:lle
.then((response) => {
navigation.navigate('SignedIn');
return onSignIn(STORAGE_KEY, response.token);
})
Upvotes: 1
Reputation: 804
There is no using method on this.loginUser()
this.loginUser().then(() => navigate('SignedIn'));
Can you try this? it will work.
loginUser() {
const { email, password,} = this.state;
const { navigate } = this.props.navigation;
//tähän myöhemmin virheiden käsittely
return axios.post("https://*******.com/auth",{
email: email,
password: password
})
// apista saatu token annetaan arvoksi STORAGE_KEY:lle
.then((response) => {
return onSignIn(STORAGE_KEY, response.token);
})
.then(() => navigate('SignedIn'))
}
Upvotes: 0