-
-
Save DomenicoColandrea86/2159237808698bae154b97d9ee391eae to your computer and use it in GitHub Desktop.
React-Navigation AuthFlow with Saga
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { effects } from 'redux-saga'; | |
import { NavigationActions } from 'react-navigation'; | |
import { redirect } from './action'; | |
import NavigationConfiguration from '../configuration/NavigationConfiguration'; | |
import { | |
REDIRECT, | |
AUTHENTICATE, | |
UNAUTHENTICATE, | |
} from './constants'; | |
const navConfig = new NavigationConfiguration(); | |
const isAuthenticatedRouteName = navConfig.isAuthenticatedRouteName; | |
const isUnauthenticatedRouteName = navConfig.isUnauthenticatedRouteName; | |
const initialAuthenticatedRouteName = navConfig.getInitialAuthenticatedRouteName(); | |
const initialUnauthenticatedRouteName = navConfig.getInitialUnauthenticatedRouteName(); | |
function* redirectFlow() { | |
const state = yield effects.select(); | |
const authenticated = state.auth.authenticated; | |
const index = state.nav.index; | |
const routeName = state.nav.routes[index].routeName; | |
const redirectRoute = (name, childRouteName) => NavigationActions.reset({ | |
index: 0, | |
actions: [ | |
NavigationActions.navigate({ routeName: name }) | |
], | |
}); | |
if (authenticated && !isAuthenticatedRouteName(routeName)) { | |
yield effects.put(redirectRoute(initialAuthenticatedRouteName)) | |
} else if (!authenticated && !isUnauthenticatedRouteName(routeName)) { | |
yield effects.put(redirectRoute(initialUnauthenticatedRouteName)) | |
} | |
} | |
function* authenticateFlow() { | |
yield effects.put(redirect()); | |
} | |
function* unauthenticateFlow() { | |
yield effects.put(redirect()); | |
} | |
export default function* root() { | |
yield effects.takeLatest(REDIRECT, redirectFlow); | |
yield effects.takeLatest(AUTHENTICATE, authenticateFlow); | |
yield effects.takeLatest(UNAUTHENTICATE, unauthenticateFlow); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react' | |
import { connect } from 'react-redux' | |
import { redirect as redirectAction } from 'src/redux/auth/action'; | |
class Index extends React.Component { | |
static propTypes = { | |
redirect: React.PropTypes.func.isRequired, | |
}; | |
componentDidMount() { | |
this.props.redirect(); | |
} | |
render() { | |
return null; | |
} | |
} | |
export default connect(null, { redirect: () => redirectAction() })(Index); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment