I’m not sure where the error in my logic is? Apologies in advance for nooby question, am new to React and Firebase.
I have a sign-in page followed by a profile page to be protected. My logic in the PrivateRoute is that: If the user is authenticated, the authorised
will be set to true and so the user will be directed to the profile page. And otherwise, the user will be directed back to the SignIn page.
My issue is that even when the user is signed in successfully, the user is unable to go to /profile and keeps getting redirected to /sign-in. Why is that?
Code for Protected route:
import { getAuth, onAuthStateChanged } from "firebase/auth";
import { Navigate, Outlet } from "react-router-dom";
import { useState, useEffect } from "react";
const PrivateRoute = () => {
const auth = getAuth();
const [authorised, setAuthorised] = useState(false);
onAuthStateChanged(auth, (user) => {
if (user) {
setAuthorised(true);
}
if (!user) {
setAuthorised(false);
}
});
return(
authorised ? <Outlet/> : <Navigate to="/sign-in"/>
)
}
export default PrivateRoute;
Code for App.js
import { Route, Routes } from "react-router-dom";
import Profile from "./pages/Profile"
function App() {
return (
<div>
<Route path="/sign-in" element={<SignIn />} />
<Route element={<PrivateRoute />}>
<Route path="/profile" element={<Profile />} />
</Route>
);
}
Appreciate any help, and thank you in advance
2
Answers
I think it is because
authorised
is false on mount, so it redirects tosign-in
. In your code, PrivateRoute is working withprofile
and not working withsign-in
. It means after redirects tosign-in
, you can’t go back toprofile
even user has been signed in.Please refer React-Router-Dom unable to render page but routes back due to PrivateRoute for more details.
Because onAuthStateChanged is asynchronous, your useState may be checking before receiving any information from Firebase. I suggest you use react-firebase-hooks and take advantage of the useAuthState function.
}