Skip to content

Instantly share code, notes, and snippets.

@JimmyLv
Created July 13, 2017 05:33
Show Gist options
  • Save JimmyLv/72db0bc54012b703f8eb5811fea07333 to your computer and use it in GitHub Desktop.
Save JimmyLv/72db0bc54012b703f8eb5811fea07333 to your computer and use it in GitHub Desktop.
HOC AuthedComonent
import React, { Component } from 'react';
import userStorage from '../shared/storage/user';
import history from '../history';
const connectAuthCheck = doCheckFn => (Comp) => {
class AuthedComonent extends Component {
state = {
authed: false,
};
componentWillMount() {
Promise.resolve(doCheckFn(this.props))
.then(
() => this.setState({ authed: true }),
(e) => { console.error('Auth failed:', e); },
);
}
render() {
return this.state.authed ? <Comp {...this.props} /> : <div>hidden</div>;
}
}
return AuthedComonent;
};
const connectCheckLogin = connectAuthCheck(() =>
userStorage.getUser()
.catch((e) => {
history.push('/sign-in');
throw e;
}));
export default connectCheckLogin;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment