I'm using the supabase authentication system in my expo app and I'd like to know how to redirect the user to the Login screen when he's not logged in. I've followed the instructions but even if I log in, I'm still redirected to the Login screen.
export default function Home({navigation, session}) {
useEffect(() => {
if (!session?.user) navigation.navigate('Login');
}, [session]);
return (
)
}
Edit
I update my code to something like that :
const [session, setSession] = useState(null);
useEffect(() => {
supabase.auth.getSession().then(({ data: { session } }) => {
setSession(session);
})
supabase.auth.onAuthStateChange((event, session) => {
setSession(session);
})
if (!session?.user) navigation.navigate('Login')
}, []);
You had the check for whether the user is signed in or not before getting the value of session. You have to put it inside your callbacks to first get the value and then redirect. The onAuthStateChange
fires with the initial session (or null), so you should be able to just setup the onAuthStateChange
listener to get the initial session as well.
const [session, setSession] = useState(null);
useEffect(() => {
supabase.auth.onAuthStateChange((event, session) => {
setSession(session);
if (!session?.user) navigation.navigate('Login')
})
}, []);