Dynamically navigating between stacks with react-navigation 5

依然范特西╮ 提交于 2021-02-11 14:22:47

问题


I'm trying to dynamically navigate between stacks via a single fetch from a server, which reads a token from the device, and makes a server request to update isUserExists.

if isUserExists is false, render AuthStack, otherwise render AppStack.

My code:

Example for AuthStack.js:

import React from "react";
import { createStackNavigator } from "@react-navigation/stack";
import { Auth, Registration, Login, VerifyAuth } from "../../screens/auth";

const Stack = createStackNavigator();

const AuthStack = () => {
  return (
    <Stack.Navigator initialRouteName="Auth">
      <Stack.Screen name="Auth" component={Auth} />

      <Stack.Screen name="Registration" component={Registration} />

      <Stack.Screen name="Login" component={Login} />

      <Stack.Screen name="VerifyAuth" component={VerifyAuth} />
    </Stack.Navigator>
  );
};

export default AuthStack;

AppNavigator.js

const AppNavigator = () => {
  const dispatch = useDispatch();
  const isUserExists = useSelector((state) => state.auth.isUserExists);

  const [allowNavigate, setAllowNavigate] = useState(false);

  const fetchData = async () => {
    const token = await TokensHandler.getTokenFromDevice();
    if (token === null) {
      dispatch(setIsUserExists(false));
      setAllowNavigate(true);
    } else
      dispatch(isUserExistsByToken(token)).then(() => setAllowNavigate(true));
  };

  useEffect(() => {
    fetchData();
  }, []);

  return (
    <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
      {allowNavigate ? (
        <View>
          <ActivityIndicator size="large" />
          <StatusBar barStyle="default" />
        </View>
      ) : (
        <NavigationContainer>
          {isUserExists ? <AppStack /> : <AuthStack />}
        </NavigationContainer>
      )}
    </View>
  );
};

export default AppNavigator;

My problem is that the component does not re-renders when isUserExists prop updates after fetch is complete.

How can I handle that?

Am I even doing this right? I feel like I can clean up my code and I just don't know how.

Thanks for the help.

来源:https://stackoverflow.com/questions/62970998/dynamically-navigating-between-stacks-with-react-navigation-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!