I am trying to navigate a user on login, however it seems like onAuthStateChanged does not work correctly as after logging in, the currentUser is still null and as such is navigated to the home page even though they are supposed to be navigated to a verification page (protected navigation). Below is the relevant code in the AuthContext file.
export default function AuthContextProvider({ children }) {
const [currentUser, setCurrentUser] = useState(null)
const [loading, setLoading] = useState(true)
useEffect(() => {
const unsubscribe = onAuthStateChanged(auth, (user) => {
setCurrentUser(user)
setLoading(false)
})
return () => {
unsubscribe()
}
}, [])
}
The relevant login function is here
try {
setLoading(true)
await login(email, pw).then(response => {
console.log(currentUser)
navigate('/verification')
})
} catch(error) {
if(error.code === "auth/user-not-found") {
console.log(error.message)
setError("Account does not exist. Please try again with a different email or create a new account.")
}
if(error.code === "auth/wrong-password") {
console.log(error.message)
setError("Wrong password. Please try again with a different password.")
}
}
setLoading(false)
And finally the protected route is here
const router = createBrowserRouter(
createRoutesFromElements(
<Route path='/' element={<Layout />}>
<Route exact index element={<HomePage />} />
<Route exact path='/signup' element={<SignUp />} />
<Route exact path='/login' element={<Login />} />
<Route element={<ProtectedRoute />}>
<Route exact path='/verification' element={<Verification />} />
</Route>
<Route path='*' element={<Error404 />} />
</Route>
)
);
function ProtectedRoute({children}) {
const {currentUser} = useAuth()
if(currentUser === null) {
return <HomePage />
}
return currentUser ? <Outlet/> : <Navigate to="/" />
}
This issue only occurs on the first log in where the navigation goes to the home page. However when I manually type "/verification" on the address bar I am routed correctly to the verification page and on console log shows as logged in. So I feel it is logging in, but there is some form of delay (but I have an await
call so unsure why the page does not wait for the user to be set before rendering the page)
I am on firebase v10.1 and react-router 6.4
Edit: After changing to a new protected route code (edited in the code block), the redirection works, however, when I am logged out and I try to access the /verification route, my code does not redirect to homepage. I need it to be able to redirect to the homepage when the user is not logged in and tries to access the verification. I have added a codesandbox https://codesandbox.io/p/sandbox/flamboyant-haibt-hwrhzj
This shows the issue I have on hand. The relevant routes if needed are:
/login
/signup
/verification