Question: creating "gated" react components

Question

creating "gated" react components

Answers 1
Added at 2016-08-03 17:08
Tags
Question

so I have an app that is using Reflux router and I want to create admin only areas in the app. what I'm trying to achieve is when a user goes to a gated part of the app that part of the app will make an API call to check of the user is authorized to access that component (via a token that is read on the server) and if they are not authorized then it will re-direct them to the login component.

but I've run into a conundrum with best practices within react. react says that ajax (or in this case an API call) should be done in componentDidMount rather than componentWillMount, but from my understanding about the react life cycle if I follow their best practice then the component would/could be rendered before the user is authenticated which is extremely undesirable especially if the server latency is not fast enough.

What is the best way to handle something like this within react?

Answers to

creating "gated" react components

nr: #1 dodano: 2016-08-03 17:08

You don't need to make the ajax request on the exact component you want to display after the token is approved, it can be any component, such as one that wraps the private information.

class AuthWrapper extends Component {
  componentDidMount() {
    ajax(url).then(token => {
      if (token) this.setState({ token })
      else redirect()
    })
  }

  render() {
    return (
      <div>
        {this.state.token && this.props.children}
        {!this.state.token && <div>Fetching...</div>}
      </div>
    )
  }
}

Then somewhere else:

<AuthWrapper>
  <YourPrivateComponent />
<AuthWrapper>
Source Show
◀ Wstecz