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?