Home > other >  Android App Splash screen not loading instantly - React Native
Android App Splash screen not loading instantly - React Native

Time:10-05

I'm relatively new to react native and I've been trying to write this code where I get user type (i.e Admin or Mod) from my database and switching to the respective drawer navigator. In between switching I'm loading my splash screen. My problem is say I login as an Admin then logout and try to login as a Mod, for a split second before my Splash Screen is loaded, My previous screen (i.e Admin screen) renders. Any help would be greatly appreciated.

const App = () => {
  const [isLoading, setIsLoading] = useState(true);
  const [userType, setUserType] = useState(null);
  const [User, setUser] = useState(null);

  const getUserType = async () => {
    //Getting UserType from Database
    setUserType(fetchedUserType);
  };

  const onAuthStateChanged = user => {
    setUser(user);
    setTimeout(() => {
      if (isLoading) setIsLoading(false);
    }, 2000);
  };

  useEffect(() => {
    const subscriber = auth().onAuthStateChanged(onAuthStateChanged);
    return subscriber;
  });

  useEffect(() => {
    //clearing the UserType and making the splash screen render
    setUserType(null);
    setIsLoading(true);
    let Mounted = true;
    getUserType().then(() => {
      if (Mounted) {
        setIsLoading(false);
      }
      return function cleanup() {
        Mounted = false;
      };
    });
  }, [User]);

  if (isLoading) {
    return <Splash></Splash>;
  } else if (User === null) {
    return <Login></Login>;
  } else if (userType === 'Admin') {
    return <AdminDrawerNavigator></AdminDrawerNavigator>;
  } else if (userType === 'Mod') {
    return <ModDrawerNavigator></ModDrawerNavigator>;
  } else {
    return <Fatal></Fatal>;
  }
};

CodePudding user response:

Try adding in render:

if(userType===null){
    return null;
}
if (isLoading) {
    return <Splash></Splash>;
} else if (User === null) {
   return <Login></Login>;
} else if (userType === 'Admin') {
    return <AdminDrawerNavigator></AdminDrawerNavigator>;
} else if (userType === 'Mod') {
    return <ModDrawerNavigator></ModDrawerNavigator>;
} else {
    return <Fatal></Fatal>;
}

CodePudding user response:

Was able to fix this issue by removing the setUserType(null) in the second useEffect.

  • Related