I have this structure in my React Native with expo router at my app/_layout.tsx level. Below is my code. I am trying to fix the issue and error that I am getting when the app loads. Essentially I am trying to check if use is logged in, if not take them to log in screen or to HomeScreen (app/(tabs)
// app/_layout.tsx
SplashScreen.preventAutoHideAsync();
export default function RootLayout() {
const colorScheme = useColorScheme();
const [loaded] = useFonts({
SpaceMono: require("../assets/fonts/SpaceMono-Regular.ttf"),
});
const [isLoggedIn, setIsLoggedIn] = useState<boolean | null>(null);
const router = useRouter();
useEffect(() => {
async function initializeAuth() {
const loggedIn = await checkAuthStatus();
setIsLoggedIn(loggedIn);
SplashScreen.hideAsync();
}
initializeAuth();
}, []);
useEffect(() => {
if (isLoggedIn === false) {
router.replace("/(auth)/LoginScreen");
}
}, [isLoggedIn]);
if (!loaded || isLoggedIn === null) {
return null;
}
return (
<GestureHandlerRootView style={{ flex: 1 }}>
<ThemeProvider value={colorScheme === "dark" ? DarkTheme : DefaultTheme}>
<Stack screenOptions={{ headerShown: false }}>
<Slot />
</Stack>
</ThemeProvider>
</GestureHandlerRootView>
);
}
authUtils.js
import * as SecureStore from "expo-secure-store";
// Utility to check if a user token is saved
export async function checkAuthStatus() {
const token = await SecureStore.getItemAsync("authToken");
return !!token;
}
// Utility to save token
export async function setAuthToken(token) {
await SecureStore.setItemAsync("authToken", token);
}
// Utility to clear token
export async function clearAuthToken() {
await SecureStore.deleteItemAsync("authToken");
}