Skip to content

Instantly share code, notes, and snippets.

@stackdumper
Created May 1, 2018 08:30
Show Gist options
  • Save stackdumper/f3ac32a69043d1edebc885d92f7d20ac to your computer and use it in GitHub Desktop.
Save stackdumper/f3ac32a69043d1edebc885d92f7d20ac to your computer and use it in GitHub Desktop.
import React, { Component } from 'react';
import { NavigationActions } from 'react-navigation';
import { reaction } from 'mobx';
import { inject, observer } from 'mobx-react';
const navigateWithReset = (navigation, targetRoute) => {
const resetAction = NavigationActions.reset({
index: 0,
actions: [NavigationActions.navigate({ routeName: targetRoute })],
});
navigation.dispatch(resetAction);
};
const redirectOnAuthState = (
state,
targetRoute,
resetNavigationStack,
) => (WrappedComponent) => {
class AuthorizedRedirectWrapper extends Component {
componentDidMount() {
this.checkAuthorization(this.props.userStore.authorized);
this.authChangeReactionDisposer = reaction(
() => this.props.userStore.authorized,
this.checkAuthorization.bind(this),
);
}
checkAuthorization(authorized) {
if (state === 'authorized' ? authorized : !authorized) {
if (resetNavigationStack) {
navigateWithReset(this.props.navigation, targetRoute);
} else {
this.props.navigation.navigate(targetRoute);
}
}
}
render() {
// filter unrelated props
const { userStore, ...props } = this.props;
return <WrappedComponent {...props} />;
}
}
return inject('userStore')(observer(AuthorizedRedirectWrapper));
};
export default redirectOnAuthState;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment