'(React Native) redirect login and logout to different screen respectively

I am trying to redirect screen when the following action are taken, first when I log in I want to redirect to account screen and also when I logout it should redirect to login screen, currently when I login it's take me to home screen and when I logout it also goes to home screen.

In my AuthNavigator I have the following screens Home, Listing, Login

In my AppNavigator I have the following screens Home, Listing, Account

Both AuthNavigator and AppNavigator have the below stack navigator

    <Stack.Navigator
        screenOptions={{
          headerShown: false,
        }}
        initialRouteName={ 'Home'}  
    >
        ... screen
   <Stack.Navigator />

Context.js

import React  from 'react';
const AuthContext = React.createContext();
export default AuthContext;

App.js

import AuthContext from './context';

const App = () => {
  const [user, setUser] = useState();

  return (
    <AuthContext.Provider value={{user, setUser}}>
      <NavigationContainer>
          { user ? <AppNavigator /> : <AuthNavigator/> }
      </NavigationContainer>
    </AuthContext.Provider>
  )
} 

Account.js

const Panel = ({navigation}) => {
  const { user } = useContext(AuthContext);


  return (
    <View style={styles.container}>
      <Text>Name {user.name} </Text>
      <Text>Email {user.email} </Text>
    </View>
  )
}

Login.js

const handleSubmit = async ( { email, password } ) =>{
    const response = await axios.post(userLogin, 
    { 
        email, 
        password,
    })
    .then((response) => { 
        const user = response.data;
        authContext.setUser(user);
    })
    .catch(error => { 
        console.log(error);
    }); 
}

How can I route or redirect to account screen after I sign in and to login screen after I logout Thanks for the help.



Solution 1:[1]

Why did you duplicate Home, Listing in both navigators?

You should have one navigator for them, and another one only for Login & Account screens.

AppNavigator: HomeScreen, ListingScreen

And on the Listing screen, a navigate event to the AuthNavigator to display Login or Account screen

AuthNavigator: LoginScreen, AccountScreen

where you will have the check, if Authenticated -> AccountScreen else -> LoginScreen

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Narmi