skip to Main Content

I am trying to switch navigators upon a condition of useToken exists or not. I am using asyncStorage To know if there’s a token it’s true and show app screens otherwise show authScreens.But I can’t switch between Navigators whenever i hit login i am adding token to async storage if i hit logout i am removing token from asyncStorage.The Switching of containers not happening Instantly. It’s happening on next reload or refresh . I am new to react native any resources related to this topic is appreciated. Thank you

       
App.js

const App = () => {
  const[userToken,setUserToken]=useState(null)
  useEffect(()=>{
    const getT=async()=>{
        const token=await getToken() //getting token from storage
        console.warn("auth",token)
        setUserLToken(token) //store token in local storage
     }
      getT()
    },[]
    )
    
    return(
      <NavigationContainer>
     {userToken === undefined ? <AuthStack/> : <AppStack/>}  
      </NavigationContainer>
    )
};


Appstack.js

const AppStack = () => {
  return (
      <Stack.Navigator screenOptions={{headerShown:false}}>
      <Stack.Screen name="HomeScreen" component={TabNavigator}/>
      <Stack.Screen name="Location" component={Location}/>
      <Stack.Screen name="Calltoorder" component={Calltoorder}/>
      <Stack.Screen name='Profile' component={Profile}/>
      <Stack.Screen name="EditProfile" component={EditProfile}/>
      <Stack.Screen name='ProductItem' component={ProductItem}/>
      <Stack.Screen name='SubCategories' component={SubCategories}/>
      <Stack.Screen name='Categories' component={Categories}/>
      <Stack.Screen name='CartContainer' component={CartContainer} options={{ headerShown:true }}/>
      <Stack.Screen name='MedicineCart' component={MedicineCart}/>
      <Stack.Screen name='LabCart' component={LabCart}/>
      <Stack.Screen name='OrderHistory' component={OrderHistory}/>
      <Stack.Screen name='ProductDescription' component={ProductDescription}/>
      <Stack.Screen name='Test' component={Test}/>
      <Stack.Screen name='DoctorCard' component={DoctorCard}/>
      <Stack.Screen name='DocBySpecialization' component={DocBySpecialization}/>
      <Stack.Screen name='DoctorDetails' component={DoctorDetails}/>
      <Stack.Screen name='AllTests' component={AllTests}/>
      <Stack.Screen name='AllPackages' component={AllPackages}/>      
      <Stack.Screen name='TestsAndPackagesById' component={TestsAndPackagesById}/>
      <Stack.Screen name='EmptyPage' component={EmptyPage} options={{ headerShown:true }}/>
      <Stack.Screen name='DiagSearch' component={DiagSearch}/>                                                            
      </Stack.Navigator>
  )
}

authstack.js

const AuthStack = () => {
  return (
      <Stack.Navigator screenOptions={{headerShown:false}}>
      <Stack.Screen name="Signin" component={Signin}/>
      <Stack.Screen name="Signup" component={Signup}/>  
      <Stack.Screen name="ConfirmEmail" component={ConfirmEmail}/>
      <Stack.Screen name="ForgotPass" component={ForgotPass}/>
      <Stack.Screen name="NewPass" component={NewPass}/>
      </Stack.Navigator>
  )
}

2

Answers


  1. It works like this because of the empty array of dependencies in useEffect. An empty array means, the useEffect runs only once when the page is refreshed after the components are mounted. To run it after a change happens in token, Try adding your token variable to the dependency array

    Login or Signup to reply.
  2. One way to achieve this is using a "toggle flag" to re-run useEffect whenever some event occurs (in your case, it is token update).

    In the below code, we give tokenFlag as a dependency to the useEffect. So whenever the tokenFlag state changes, useEffect will re-run. This will update your userToken and the Navigation containers will be changed.

    const App = () => {
      
      const[userToken,setUserToken] = useState(undefined)
      const[tokenFlag, toggleTokenFlag] = useState(false)
      
      useEffect(()=>{
        const getT = async ()=>{
            const token=await getToken() //getting token from storage
            console.warn("auth",token)
            setUserLToken(token) //store token in local storage
        }
        getT()
      },[tokenFlag])
        
      const login = () => {
        // your login business logic...
        toggleTokenFlag(!tokenFlag)
      }
    
      const logout = () => {
        // your logout business logic...
        toggleTokenFlag(!tokenFlag)
      }
    
      return(
        <NavigationContainer>
          {userToken === undefined ? <AuthStack/> : <AppStack/>}  
        </NavigationContainer>
      )
    };
    

    If your login & logout functions are in different files, then you might have to use global state for triggering use effect.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search