skip to Main Content

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


  1. I think it is because authorised is false on mount, so it redirects to sign-in. In your code, PrivateRoute is working with profile and not working with sign-in. It means after redirects to sign-in, you can’t go back to profile even user has been signed in.

    Please refer React-Router-Dom unable to render page but routes back due to PrivateRoute for more details.

    Login or Signup to reply.
  2. 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.

    const PrivateRoute = () => {
    const auth = getAuth();
    const [user, loading] = useAuthState(auth);
    
    if (loading) {
        return "Loading"
    }
    return user ? <Outlet /> : <Navigate to="/sign-in" />
    

    }

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search