Skip to content

Instantly share code, notes, and snippets.

@lmuntaner
Created March 18, 2018 07:13
Show Gist options
  • Save lmuntaner/2ce4f3193fea6252f5fb9c5a27b3b4a5 to your computer and use it in GitHub Desktop.
Save lmuntaner/2ce4f3193fea6252f5fb9c5a27b3b4a5 to your computer and use it in GitHub Desktop.
AuthorizedRoute Component
class AuthorizedRoute extends Component<StateProps & DispatchProps & RouteProps, {}> {
public componentWillMount() {
if (!this.props.token) {
this.props.dispatchLogin();
}
}
public render() {
const { component: RouteComponent, render, token, ...rest } = this.props;
if (!this.props.token) {
return <Route { ...rest } render={ this.renderFalse } />;
}
if (render) {
return <Route { ...rest } render={ render } />;
}
return <Route { ...rest } component={ RouteComponent } />;
}
private renderFalse = () => false;
}
interface StateProps {
token?: string;
}
const mapStateToProps = (state: AppState): StateProps => ({
token: tokenSelector(state),
});
interface DispatchProps {
dispatchLogin: () => LoginPromise;
push: (location: LocationDescriptor, state?: LocationState) => void;
}
const mapDispatchToProps = (dispatch: Dispatch) => ({
dispatchLogin: () => dispatch(login()),
});
export default connect<StateProps, DispatchProps, RouteProps>(mapStateToProps, mapDispatchToProps)(AuthorizedRoute);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment