I have a firebase onAuthStateChange and a set of private routes to be rendered with react router v6
useEffect(() => {
const fetchData = async () =>
await auth.onAuthStateChanged(async authUser => {
console.log('here in authuser')
if (authUser) {
await dispatch(setUser('SET_USER', authUser))
} else {
await dispatch(setUser('SET_USER', null))
}
})
fetchData()
}, [])
<Route path='/' element={<PrivateRoute user={users} />}>
<Route path='/courses/:id' element={<CourseDetails />} />
<Route
path='/'
element={<Courses emailId={users?.user?.email} />}
/>
<Route path='/enrolled' element={<Enrolled />} />
<Route path='/authored' element={<Authored />} />
<Route path='/users' element={<Users />} />
</Route>
In the protected route component I am checking if user is null then redirect user to login page else render the children.
if (user === null || user.user === null) {
console.log('Entered!!!!!')
return <Navigate to='/login' replace />
} else {
return children ? children : <Outlet />
}
On page refresh if I am logged in also I am redirected to login route because onauthstatechange has not finished executing. So user is null inside the
What is the right way to handle this situation and make sure that user gets navigated to the same page where reload happened.
You can create a component that handles the check for you.
So in your route you wrap your PrivateRoute with your route component like this :
<Route path='/courses/:id' element={<PrivateRoute><CourseDetails /></PrivateRoute> } />
So what this component does is check if the user is authed. If it is authed it will render the child component that is your route. If not it will redirect you to /login
they are talking about it in the docs
const PrivateRoute =({ children }: { children: JSX.Element }) => {
let auth = useAuth();
let location = useLocation();
if (!auth.user) {
// Redirect them to the /login page, but save the current location they were
// trying to go to when they were redirected. This allows us to send them
// along to that page after they login, which is a nicer user experience
// than dropping them off on the home page.
return <Navigate to="/login" state={{ from: location }} replace />;
}
return children;
}