Use Case
I want to make async()
call whenver user will try to visit private route. Generally synchronous methods are used while redirecting to private routes.
Here is my code I have used but not understanding how can I use asynchronous method with it.
class PrivateRoute extends Component {
constructor(props) {
super(props);
this.state = {
isAdmin: null
};
}
componentDidMount() {
console.log("PrivateRoute");
verifyUser().then(res => {
this.setState({
isAdmin: res
});
});
}
render() {
const { component: Component, ...rest } = this.props;
return (
<Route
{...rest}
render={props =>
this.state.isAdmin === true ? (
<InnerLayout>
<Component {...props} />
</InnerLayout>
) : this.state.isAdmin === null ? (
<div>Loading...</div>
) : (
<Redirect
to={{ pathname: "/Login", state: { from: this.props.location } }}
/>
)
}
/>
);
}
}
export default PrivateRoute;
Problem with above code is componentDidMount() calls once. I have checked React routing and private routes Question and also checked Authenticate async with react-router-v4 question but both answers didn't work for me.
If I try to resolve promise in render then it shows following error:
How can I achieve this use case?