P粉2768766632023-09-04 12:40:54
In your code, useEffect will be executed whenever the value of the session or router changes (the second parameter of useEffect). Therefore, neither if nor else are executed in the same run of useEffect, although they are executed in two different runs that may be executed in rapid succession.
This is one way to achieve what you are after.
Example implementation:
const App = (props) => { const [isLoggedIn, setIsLoggedIn] = useState(false); useEffect(()=>{ //apply the logic and set the state if(logic) setIsLoggedIn(true); },[]) return {isLoggedIn ? <ActiveApp /> : <Login />} }
P粉0356005552023-09-04 00:28:17
Finally, I found the root cause.
It comes from the supabase auth helper, it is an async function, it does not contain the status of whether it is loading or wrong, which means it is at the beginning (which means it is loading).
The simple way to solve this problem is to use directly useSessionContext
. session
will still be fetched asynchronously, but the isLoading
and error
statuses can be fetched synchronously to resolve this issue, and they can be used with useEffect# Conditional branches within ##.
import { useSessionContext } from '@supabase/auth-helpers-react' const {isLoading, session} = useSessionContext() useEffect(() => { if (isLoading) { console.debug('show loading page') } else if (session) { console.debug('stay in page') } else { console.debug('goto login') router.push('/login').then( () => { console.debug('goto login done') } ) } }, [session, isLoading, router])