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

129
Visualizações
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 à 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