Reputation: 2208
I'm new to React Native. I have coded a Login page and Profile page.
On Login.js page I have state:
this.state = {
email: '',
password: '',
authenticating: false,
}
Once you hit the Login button after entering correct details, loginUser function gets executed:
loginUser = (email, password) => {
this.setState({ authenticating: true });
try {
firebase.auth().signInWithEmailAndPassword(email, password)
.then((user) => {
this.props.navigation.navigate('Profile');
this.setState({ authenticating: false });
});
}
catch (error) {
console.log(error.toString());
}
}
Below is my render function:
renderCurrentState() {
if (this.state.authenticating) {
return (
<View>
<ActivityIndicator size='large' />
</View>
)
}
return (
<View>
<Input
placeholder='Enter your Email...'
label='Email'
onChangeText={email => this.setState({ email })}
value={this.state.email}
/>
<Input
placeholder='Enter your Password...'
label='Password'
secureTextEntry
onChangeText={password => this.setState({ password })}
value={this.state.password}
/>
<Button
onPress={() => this.loginUser(this.state.email, this.state.password)}
>Log in</Button>
<Button
onPress={() => this.signUpUser(this.state.email, this.state.password)}
>Sign upp</Button>
</View>
)
}
The problem is once I hit the login button, it starts showing the activity indicator but just before showing the 'Profile' page it shows the 'Login' page once again for few milliseconds which I don't want.
Any help on this. I dont want to put a setTimeOut delay solution like this:
setTimeout(()=>{ this.setState({ authenticating: false }) }, 100)
If someone can provide me a code for this. It would be very helpful.
Upvotes: 1
Views: 2209
Reputation: 92210
React-navigation now has lifecycle hooks. You can wait for current screen to blur so that you know the transition has completed.
navigateAsync = (routeName) => {
const promise = new Promise(resolve => {
const subscription = this.props.navigation.addListener('didBlur', () => {
subscription.remove();
resolve();
});
});
this.props.navigation.navigate(routeName);
return promise;
};
And then you can just call
this.navigateAsync('Profile').then(() => {
this.setState({ authenticating: false });
})
See https://github.com/react-navigation/rfcs/issues/11
Upvotes: 1