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

146
Visualizações
How to preserve auth status with firebase in react component

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.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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;
}
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