Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

128
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!