Home > Net >  React Navigation redirect user based on a context state
React Navigation redirect user based on a context state

Time:09-22

I have added a state called roleSelected the initial value for this roleSelected is false, which presents in my AuthContext

const [roleSelected, setRoleSelected] = useState(false);

My stack navigation screens are like this,

<Stack.Screen name={routes.LOGIN} component={Login} />
<Stack.Screen name={routes.SIGNUP} component={Signup} />
<Stack.Screen name={routes.ROLE_SELECTION} component={Role} />

What I'm trying to do: So if the roleSelection is false, no matter which screen I'm currently in this stack I want to redirect the user ROLE_SELECTION route. So for this case I added the following code in my Login and Signup screens,

const Login = ({navigation}) => {
  ...
  const {roleSelected} = useContext(AuthContext);

  useEffect(() => {
    !roleSelected && navigation.navigate(routes.ROLE_SELECTION);
    console.log(roleSelected);
  }, [navigation]);

Whenever the app starts user redirects to the ROLE_SELECTION route, but still the user can click back and go to the Login screen, I don't want that to happen. Really appreciate it if somebody could help thanks.

CodePudding user response:

Did you try instead of navigation.navigate to use navigation.reset that wipe the navigator state and replace it with a new route.

CodePudding user response:

Try Adding one more useEffect() with an empty dependency array into your code.

useEffect(() => {
    !roleSelected && navigation.navigate(routes.ROLE_SELECTION);
    console.log(roleSelected);
  }, []);
  • Related