Reputation: 1152
In my react-native application i want to show a screen based on a state.
Login.js
export default class Login extends Component {
constructor(props){
super(props);
this.state = {
accessTokenExists: false
}
}
accessvalid = () => {
tokenStorage.getToken('accesstoken')
.then(res => {
fetchTokens.validAccessToken(res)
.then(res => {
this.setState({accessTokenExists: true});
console.log('Existing Accesstoken');
})
})
.catch(err => {
this.setState({accessTokenExists: false});
console.log('Not Existing AccesToken');
})
}
componentWillMount(){
this.accessvalid();
};
componentDidMount() {
SplashScreen.hide();
}
render() {
if(this.state.accessTokenExists){
return(<Fingerprint navigation={this.props.navigation}/>)
} else {
return(<Password navigation={this.props.navigation}/>)
}
}
}
when the state accesTokenExists is true react renders first the other screen for a split second and then re-rendering the right screen.
Is this because the API calls i make before i changed the state in the accesvalid method.
Thanks for any help
Upvotes: 0
Views: 545
Reputation: 4423
Your request is asynchronous. When you make this request in ComponentWillMount it fires off the request and the component continues to render. Since the default state of this is false, <Password navigation={this.props.navigation}/>
will render.
When the return comes back, if successful, the other component will mount. You want to handle the condition of "Requesting" as a state your component could be in to handle this.
Upvotes: 1
Reputation: 6027
I believe that it is because you set it to false in the constructor, and it takes time until ComponentWillMount sets it to true. A way to handle this may be by rendering a loading nessage until finishing to check whether accessTokenExists, using another state variable that will indicate whether loading is done or not. I assume, btw, that you know that componentWillMount is deprecated.
Upvotes: 1