I am trying to implement a feature when the user logs into the app and they have not completed their profile, they should be redirected to a certain URL, So everywhere they try to go (except logout) they should be redirected to the complete-profile
URL.
I'm handling routing with react-router-dom
package.
App.js
class App extends Component {
async componentDidMount() {
const logged = isLoggedIn();
if (logged) {
const completed = await hasCompleted();
if (!completed) this.props.history.replace("/complete-profile"); //error showing here
}
}
render() {
return (
<React.Fragment>
<NavBar />
<main className="container">
<Switch>
<Route path="/complete-profile" component={CompleteProfile} />
<Route path="/login" component={Login} />
<Route path="/register" component={Register} />
<Route path="/logout" component={Logout} />
<Route path="/" exact component={Home} />
</Switch>
</main>
</React.Fragment>
);
}
}
So basically what I'm trying to do here in componentDidMount
method is: I first check if the user is logged in. Then check if the user has completed their profile, and if it's not completed then it should redirect to /complete-profile
URL.
But with this method I'm facing an error with this.props.history.replace
because it does not take any props when this method is getting called I guess, and the error that is showing is this:
Unhandled Rejection (TypeError): Cannot read property 'replace' of undefined
Which is the proper way to implement this one?
Because I dont think that I should implement these 4 lines of code checking for completed profile in every single component.