Home > Mobile >  Conditional rendering and stack navigation using useEffect
Conditional rendering and stack navigation using useEffect

Time:10-08

In my app, there is an Onboarding screen for first time using the app. When the user skips it, it saves in AsyncStorage a variable with the value 'true', which means the user has already seen the Onboarding.

In App.js I call an useEffect hook to verify the value of the variable. Since the variable is equal to 'true' it should navigate to the Home screen. The problem is that the useEffect isn't fast enough to get the variable on time and it will always go to the 'else' part of the condition. How can I code in a way that would make the useEffect obligatorily load before going to any screen?

export default function App() {
  const [boarding, setBoarding] = useState("");

  const getData = async () => {
    try {
      const value = await AsyncStorage.getItem("@storage_Key");
      console.log(value);
      if (value !== null) {
        setBoarding(value);
      }
    } catch (e) {
      // error reading value
    }
  };

  useEffect(() => {
    getData();
  });
  if (boarding == "true") {
    <NavigationContainer>
      <MainStackNavigator
        initialRoute={"Home"}
      />
    </NavigationContainer>;
  }else{
    return (
      <NavigationContainer>
        <MainStackNavigator
          initialRoute={"Onboarding"}
        />
      </NavigationContainer>
    );
  }
}

CodePudding user response:

A potential solution for you could be to use the react-native-splash-screen package to keep your Splash Screen visible whilst you perform such logic. This solution will ensure that the Onboarding screen is not visible unexpectedly.

const getData = async () => {
  try {

  } catch(e) {

  } finally {
    SplashScreen.hide(); // Called from react-native-splash-screen
  }
};

At the point where the Splash Screen is hidden, you have completed your async tasks and the boarding state variable is set to the value you are expecting.

An alternative approach would be to render a loading indicator to the User whilst getData is executing. Upon completion, the loading indicator would disappear and the correct route will be displayed.

  • Related