Passing a props component through a Stack Navigator (React Navigation v5)

Viewed 116

I am working on an expo react native application with react-navigation v5. I have created 2 navigators : one StackNavigator if the user is not signed in, and one bottomTabNavigator if he is. In the first stackNavigator, I have a screen Login which takes one prop onAuthSucces used in a TouchableOpacity like this :

<TouchableOpacity style={styles.button} onPress={this.signIn}>
   <Text style={{ color: "dimgray", fontWeight: "bold" }}>
      Se connecter
   </Text>
</TouchableOpacity>

The signIn function is written like this :

signIn = () => {
    const user = authenticationService.authenticate(
      this.state.login,
      this.state.password
    );
    if (user !== null) {
      this.props.onAuthSuccess(user);
    } else
      Alert.alert(
        "Erreur de connexion",
        "Votre identifiant et/ou votre mot de passe sont incorrects. Réessayez."
      );
  };

with a props onAuthSuccess of type : onAuthSuccess: (loggedUser: User) => void;

I tried to create a StackNavigator which can take parameters, and will affect these to the Login props, with :

const LoginPageStack = createStackNavigator<RootStackParamList>();
export const LoginStackScreen = (onAuthSuccess: any) => {
  return (
    <NavigationContainer>
      <LoginPageStack.Navigator screenOptions={{ headerShown: false }}>
        <LoginPageStack.Screen name="Login">
          {(props) => <Login {...props} onAuthSuccess={onAuthSuccess} />}
        </LoginPageStack.Screen>
        <LoginPageStack.Screen name="Register" component={Register} />
      </LoginPageStack.Navigator>
    </NavigationContainer>
  );
};

Finally, in App.tsx I use these different pages this like :

interface AppState {
  currentUser: User | null;
  isConnected: boolean;
}

export default class App extends Component<AppState> {
  state: AppState = {
    currentUser: null,
    isConnected: false,
  };

  updateCurrentUser = (loggedUser: User) => {
    this.setState({ currentUser: loggedUser });
    this.setState({ isConnected: true });
  };

  render() {
    if (this.state.isConnected) return <MainTabNavigator />;
    else {
      return (
        <LoginStackScreen onAuthSuccess={this.updateCurrentUser} />
      );
   }
}

But when I try to connect me with a login and a password that are stocked in the database, Expo Go tells me : "TypeError: _this.props.onAuthSuccess is not a function. (In '_this.props.onAuthSuccess(user)', '_this.props.onAuthSuccess' is an instance of Object)"

Do you have any idea from where the problem can come ? I don't understand.

Thank you !

0 Answers
Related