I am trying to build a Higher Order Component that would be used to protect routes.It would check (via a network call, not from cache) for the current user, and if not found, would redirect to /login.
Any ideas on how to do so?
I am trying to build a Higher Order Component that would be used to protect routes.It would check (via a network call, not from cache) for the current user, and if not found, would redirect to /login.
Any ideas on how to do so?
First understand how React HOC works. I'll try to answer this using the pseudo code.
HOC.jsx
export default (Component) => class HOC extends React.Component {
constructor(){
super()
this.state = {
waiting: true,
}
}
componentDidMount() {
this.props.actions.validateUser() // your network call to validate user
.then(() => {
// do your stuff
this.setState({
waiting: false,
})
})
.catch(() => {
// handle redirect using react-router
})
}
render() {
if(this.state.waiting) {
// Add a loader here
return <h1>Loading...</h1>
}
return <Component {...this.props} />
}
}
Component.jsx
import HOC from './HOC.jsx'
class Comp extends React.Component {
render() {
return <h1>I'm a valid user</h1>
}
}
export default HOC(Comp)
When any component uses the HOC, the network call will be executed on mount (can be moved to componentWillMount
as well) and based on the response the component will be rendered.
Hope this helps!