Reputation: 8118
I'm new to react native and I followed the Authentication flows tutorial from react native. Now I'm using typescript and I think that has something to do with it. Because when I just copy the javascript example it works.
export default class SignInScreen extends Component<NavigationScreenProps> {
constructor(props: NavigationScreenProps) {
super(props);
}
render() {
return (
<View style={styles.container}>
<Text>Sign in</Text>
<Button title="Sign in!" onPress={this.signIn}/>
</View>
);
}
private async signIn() {
//await AsyncStorage.setItem('userToken', 'abc');
console.log("PROPS", this.props);
this.props.navigation.navigate('App');
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
}
});
AuthLoadingScreen
export default class AuthLoadingScreen extends Component<NavigationScreenProps> {
constructor(props: NavigationScreenProps) {
super(props);
this.bootstrap();
}
private async bootstrap() {
console.log("AUTH props", this.props);
try {
const userToken = await AsyncStorage.getItem('userToken');
this.props.navigation.navigate(userToken ? 'App' : 'Auth');
} catch (err) {
console.log('Error', err.message);
}
}
render() {
return (
<View>
<ActivityIndicator />
<StatusBar barStyle="default" />
</View>
);
}
}
App.tsx
const AppStack = createBottomTabNavigator({
Home: HomeScreen,
Settings: SettingsScreen,
});
const AuthStack = createStackNavigator({ SignIn: SignInScreen });
export default createAppContainer(createSwitchNavigator(
{
AuthLoading: AuthLoadingScreen,
App: AppStack,
Auth: AuthStack,
},
{
initialRouteName: 'AuthLoading',
}
));
Now on the AuthLoadingScreen the props are not undefined and I push to the SignInScreen but when I click on the button the props are undefined. I have no idea why because all the examples I find are doing it this way?
Upvotes: 1
Views: 217
Reputation: 5051
That's because this
is not within the context you expect it to be. The function is unbounded, so this
doesn't contain props
. Here's how you bind it:
<Button title="Sign in!" onPress={this.signIn.bind(this)}/>
You can also use the following, without bind
ing:
<Button title="Sign in!" onPress={() => { this.signIn() }}/>
Although I prefer the first example.
Upvotes: 1