This is the useEffect
code in the React component.
import { useSession } from '@supabase/auth-helpers-react' const session = useSession() useEffect(() => { if (session) { console.debug('stay in page') } else { console.debug('goto login') router.push('/login').then( () => { console.debug('goto login done') } ) } }, [session, router])
It uses supabase to manage authentication (session).
There is a very strange problem when refreshing the page (there is no problem at all with login and logout redirection through the router, it only appears when the page is refreshed.), both branches will be reached, so in the js console, we can see Log conditional branch from two branches.
"Stay on page"
and Go to login
/Go to login complete
.
I think this is due to the
session
changing after the refresh. The first time it is undefined, the second branchrouter.push
is triggered. When the session is found, the first branchstays on the page
is triggered immediately.
Any suggestions on how to get around it? Or are there any good practices for handling page refreshes in React/NextJS? Or has anyone encountered similar or the same problem before?
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:
Finally, I found the root cause.
It comes from thesupabase 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 touse directly
The new code will look like this:useSessionContext
.session
will still be fetched asynchronously, but theisLoading
anderror
statuses can be fetched synchronously to resolve this issue, and they can be used withuseEffect# Conditional branches within ##.