Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

101
Vistas
React / firebase app flashes login screen before auth finishes

When you signup/ login/ refresh the page the login page flashes just before going to the correct page. I tried putting a loader in but all it does is do a loader animation before it flashes then goes to correct page. Any idea how to get this to not happen?

function App(){
  const [user, setUser] = useState();
  const [loading, setLoad] = useState(true);
  useEffect(() => {
    const unsubscribe = onAuthStateChanged(getAuth(), setUser, setLoad(false))
    return () => {unsubscribe()}
  }, [])
const AuthenticatedRoute = ({children}) => {
  let isAuthenticated;
    if(user !=null){
      isAuthenticated = true;
    }else{
      isAuthenticated = false;
    }
    if(!loading){
      return isAuthenticated? children: <Navigate to="/signin"/>
    }else{
      return <Loading/>
    }
  
}

const UnauthenticatedRoute = ({children}) => {
  let isAuthenticated;
    if(user !=null){
      isAuthenticated = true;
    }else{
      isAuthenticated = false;
    }
    if(!loading){
      return !isAuthenticated? children: <Navigate to="/home"/>
    }else{
      return <Loading/>
    }
  
}

      return(
      <Router>
      <div className="App">
          {
          <Routes>
            <Route exact path="/" element={<UnauthenticatedRoute><PreHome/></UnauthenticatedRoute>}/>
            <Route path='/home' element={<AuthenticatedRoute><Home/></AuthenticatedRoute>} />
            <Route exact path="/signin" element={<UnauthenticatedRoute><Signin/></UnauthenticatedRoute>} />
            <Route exact path="/signup" element={<UnauthenticatedRoute><Signup/></UnauthenticatedRoute>} />
          </Routes>
          }
      </div>
      </Router>
      )
  }

Sign Out code: This one line has been working for signing out

<button onClick={() => signOut(getAuth())}>Sign Out</button>

Sign In code:

async function OnFormSubmit(e){
        e.preventDefault();
        const auth = getAuth();
        try{
            isLoading(true);
            await signInWithEmailAndPassword(auth, email, pw)
            isLoading(false);
        }catch(err){
            console.log(err)
        }
    }
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Issues

  1. The loading state is only cleared when there's an error in onAuthStateChanged.
  2. The route protector components are declared inside another React component. This is anti-pattern. When new "instances" of these components are declared each time the parent App component rerenders, it will unmount/mount the component's subReactTree.
  3. The components don't wait for the user's authentication status to resolve before deciding to redirect or render the routed content.

Solution

  • Move the route protector components out on their own. Render an Outlet for nested routes to be rendered into. This allows you to render these as layout routes instead of individual wrapper components.
  • Use a proper "loading" state. Use undefined user state as the "loading state".

Example:

import { Outlet, Navigate } from 'react-router-dom';

const AuthenticatedRoute = ({ user }) => {
  if (user === undefined) return <Loading />;

  return user
    ? <Outlet />
    : <Navigate to="/signin" />;
};

const UnauthenticatedRoute = ({ user }) => {
  if (user === undefined) return <Loading />;

  return user
    ? <Navigate to="/home" />
    : <Outlet />;
};

...

function App(){
  const [user, setUser] = useState();

  useEffect(() => {
    const unsubscribe = onAuthStateChanged(getAuth(), setUser);
    return unsubscribe;
  }, []);

  return(
    <AuthContextProvider>
      <Router>
        <div className="App">
          <Routes>
            <Route element={<UnauthenticatedRoute user={user} />}>
              <Route path="/" element={<PreHome />} />
              <Route path="/signin" element={<Signin />} />
              <Route path="/signup" element={<Signup />} />
            </Route>
            <Route element={<AuthenticatedRoute user={user} />}>
              <Route path='/home' element={<Home />} />
            </Route>
          </Routes>
        </div>
      </Router>
    </AuthContextProvider>
  );
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda