betomoedano / Code-with-Beto-Mobile-App

Mobile app where codewithbeto.dev community can interact and learn
10 stars 3 forks source link

Problem with Routing #2

Open maimunahmed2 opened 2 months ago

maimunahmed2 commented 2 months ago

Steps to Reproduce:

  1. Navigate to the auth page (ie, an unprotected route) after signing out.
  2. Try to navigate on to a protected route from there for more than once.
  3. User gets redirected to the auth route only for the first time and not after that.

Expected Behavior:

The useProtectedRoute should redirect the user back to the auth route every time the user tries to visit protected route.

Actual Behavior:

User gets redirected to the auth route only for the first time and not after that.

Code Snippet Causing The Issue:

function useProtectedRoute(user: User) {
  const segments = useSegments();
  const navigationState = useRootNavigationState();

  const [hasNavigated, setHasNavigated] = React.useState(false);

  React.useEffect(() => {
    if (!navigationState?.key || hasNavigated) return;
    const inAuthGroup = segments[0] === "(auth)";

    if (!user.uid && !inAuthGroup) {
      router.replace("/(auth)/sign-in");
      setHasNavigated(true);
    } else if (user.uid && inAuthGroup) {
      router.replace("/(tabs)");
      setHasNavigated(true);
    }
  }, [user.uid, segments, navigationState, hasNavigated]);
}

Requested Action

I would like to open a pull request to address this issue.

betomoedano commented 2 months ago

PR is welcome