2

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?

Ayan
  • 8,192
  • 4
  • 46
  • 51
  • 1
    Possible Duplicate of [performing-authentication-on-routes-with-react-router-v4](https://stackoverflow.com/questions/47627818/performing-authentication-on-routes-with-react-router-v4/47628941#47628941) – Shubham Khatri Feb 22 '18 at 06:04

1 Answers1

2

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!

Pranesh Ravi
  • 18,642
  • 9
  • 46
  • 70