React Navigation 5 Auth Flow

后端 未结 2 1301
予麋鹿
予麋鹿 2021-01-29 04:56

In my React Native app, I\'m using React Navigation 5 and trying to route users to authentication stack if the user is not authenticated i.e. there\'s

相关标签:
2条回答
  • 2021-01-29 05:34

    I suggest you to use some loader. Load data from your AsyncStorage check if the token was valid and refresh if it is not, load user profile and do more your initialization staff. In code you would do this!

    let Loader=()=>{
    const [loadingData, setLoading]= useState(null);
    let effect=async ()=>{
        let credentials = await AsyncStorage.getItem(“data”)
        setLoading(credentials||{})
    }
    useEffect(()=>effect())
    If (loadingData===null)
         return <LoadingView/>
    return <YourRouter {...{loadingData}}/>
    
    0 讨论(0)
  • 2021-01-29 05:36

    You have to wait for getting a token from AsyncStorage like this.

    const App = () => {
    
    const [loading, setLoading] = usState(true)
    const [authenticated, setAuthenticated] = usState(false)
    
    useEffect(()=>{async()=>{
    
     const authenticatedUser = await AsyncStorage.getItem("access_token");
    
     setLoading(false)
    
      if(authenticatedUser !== null) setAuthenticated(true)
    
     }},[])
    
      const authenticatedUser = AsyncStorage.getItem("access_token");
      return (
        <Provider store={store}>
          <NavigationContainer>
            { loading &&
             <ActivityIndictor size='small' />
            }
            {
              authenticated && !loading
              ? <RootNavigator />
              : <AuthNavigator />
            }
          </NavigationContainer>
        </Provider>
      );
    };
    
    export default App;
    
    0 讨论(0)
提交回复
热议问题