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

147
Vistas
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 Respuestas
Responde la pregunta

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