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

130
Vistas
How to handle double layer protective route wrapper in React

I have created a protective Route wrapper component to restrict access to other components if the user is not logged in.

import React from 'react'
import { Route, Redirect } from 'react-router-dom'
import { useAuthContext} from '../AuthContext'

export default function PrivateRoute({ component: Component, ...rest }) {

    const { currentUser } = useAuthContext()

    return (
        <Route {...rest} render={props => {
            if (!currentUser) {
                return <Redirect to="/login" />
            } else {
                return <Component { ...props } />
            }
        }} />
    )
}

This works fine, but then I wanted to add another layer for when the user has logged in for the first time and it has to finish its registration, so if there is no firstNameDb (which is required) in the database the access to other pages than /profile should be restricted:

import React from 'react'
import { Route, Redirect } from 'react-router-dom'
import { useAuthContext} from '../AuthContext'

export default function PrivateRoute({ component: Component, ...rest }) {

    const { currentUser, userData: { firstNameDb } } = useAuthContext()

    return (
        <Route {...rest} render={props => {
            if (!currentUser) {
                return <Redirect to="/login" />
            } else if (!firstNameDb) {
                return <Redirect to="/profile" />
            } else {
                return <Component { ...props } />
            }
        }} />
    )
}

This also works fine, but only when the user is for the first time in the app and finishes registration. For the rest of the cases, when the user already finished the registration and logged in, this doesn't, because firstNameDb always starts empty "" and takes a bit of time to setState and get populated from the API call, and wherever you will find yourself in the app and refresh the page, you will always end up in /profile.

AuthContext.js
...
const [userData, setUserData] = useState({
   firstNameDb: "",
   ...
})

What would be a way to avoid this or the best way to solve this kind of permission?

about 4 years ago · Santiago Trujillo
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