AsyncStorage getItem method is invoked slow

Viewed 285

I have create a authentication flow using React Native AsyncStorage. I have invoked getItem method in useEfffect hooks and token save on state. on the basis of token the user will go on dashboard or not. But when i open the app then in useEffect hook getItem invoked very slow and at that time the sign in screen is visible then after some time user moved to dashboard so, it very slow.How can i solve it.

Code:

const App = () => {
  const [userlogin, setUserLogin] = useState(false);

  const [token, setToken] = useState("");

  const authContext = useMemo(
    () => ({
      signIn: () => {
       
      },
      signOut: () => {
        
      },
    }),
    []
  );

  const getToken = async () => {
    AsyncStorage.getItem("@Token").then((res) => {
      const token = JSON.parse(res);
      console.log("1", token);
      setToken(token);
    });
  };
  useEffect(() => {
    getToken();
  }, []);
  console.log("2", token);
  return (
    <AuthContext.Provider value={authContext}>
      <NavigationContainer>
        {token && token ? <MainNavigation /> : <AuthStackScreen />}
      </NavigationContainer>
    </AuthContext.Provider>
  );
};

export default App;
1 Answers

AsyncStorage.getItem() is an asynchronous task just like API calls. Simply add a loader screen for that.

    <NavigationContainer>
      <Stack.Navigator screenOptions={{headerShown: false}}>
        {authState.isLoading ? (
          <Stack.Screen name="Splash" component={Splash} /> // loader screen
        ) : authState.userToken == null ? (
          <Stack.Screen name="AuthNavigator" component={AuthNavigator} />
        ) : (
          <Stack.Screen name="MainNavigator" component={MainNavigator} />
        )}
      </Stack.Navigator>
    </NavigationContainer>
Related