Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

100
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda