How can we use redux to create protected routes in react-navigation?
Consider I have a redux store containing following state
const mapStateToProps = state => {
return {
isAuthenticated: state.profileInfo.isAuthenticated,
isLoaded: state.profileInfo.isLoaded,
googleProfileLoading: state.profileInfo.googleProfileLoading
}
};
And I am using React-navigation to navigate user.
const loginNavigation = createStackNavigator(
{
login: {
screen: Login
},
signup: {
screen: Signup
}
},
{
headerMode: "none"
}
)
const allRoutes = createSwitchNavigator(
{
home: {
screen: loginNavigation
},
user: {
screen: user
},
{
initialRouteName: "home"
}
);
const App = createAppContainer(allRoutes);
Now if user is not logged in, I want redirect to login screen.
In simple react-redux, this is what I usually used to do: .js
Can someone help me in figuring out how can we create protected routes in react-native, redux and react-navigation
How can we use redux to create protected routes in react-navigation?
Consider I have a redux store containing following state
const mapStateToProps = state => {
return {
isAuthenticated: state.profileInfo.isAuthenticated,
isLoaded: state.profileInfo.isLoaded,
googleProfileLoading: state.profileInfo.googleProfileLoading
}
};
And I am using React-navigation to navigate user.
const loginNavigation = createStackNavigator(
{
login: {
screen: Login
},
signup: {
screen: Signup
}
},
{
headerMode: "none"
}
)
const allRoutes = createSwitchNavigator(
{
home: {
screen: loginNavigation
},
user: {
screen: user
},
{
initialRouteName: "home"
}
);
const App = createAppContainer(allRoutes);
Now if user is not logged in, I want redirect to login screen.
In simple react-redux, this is what I usually used to do: https://github./irohitb/SelfieApp/blob/master/client/src/routes.js
Can someone help me in figuring out how can we create protected routes in react-native, redux and react-navigation
Share Improve this question edited Jul 20, 2020 at 7:15 Hristo Eftimov 15.8k14 gold badges54 silver badges79 bronze badges asked Mar 12, 2019 at 16:58 AlwaysblueAlwaysblue 12k44 gold badges141 silver badges252 bronze badges3 Answers
Reset to default 8 +50react-navigation has createSwitchNavigator
exactly for cases like this Authentication Flow.
You have to group your protected routes in one MainStack. Use createStackNavigator
:
const MainStack = createStackNavigator(
{
home: { screen: HomeScreen },
events: { screen: EventsScreen },
profile: { screen: ProfileScreen },
...
{
initialRouteName: "home"
}
);
Then, config your authentication stack, again using createStackNavigator
:
const AuthStack = createStackNavigator({
login: { screen: LoginScreen },
register: { screen: RegisterScreen },
forgot: { screen: ForgottenPasswordScreen },
...
});
And now is ing the createSwitchNavigator
- to load the MainStack
stack or the AuthStack
:
const Routes = createSwitchNavigator({
initialLoading: InitialLoadingScreen,
auth: AuthStack,
all: MainStack,
}, {
initialRouteName: 'initialLoading',
});
export default createAppContainer(Routes);
The createSwitchNavigator
will load InitialLoadingScreen
that holds the logic if the user is authenticated or not:
class InitialLoadingScreen extends React.Component {
constructor(props) {
super(props);
this.bootstrapAsync();
}
bootstrapAsync = async () => {
// Load the home screen for the logged in users
if (this.props.isAuthenticated) {
return this.props.navigation.navigate('home');
}
// load the Auth screen if the user is NOT logged in
this.props.navigation.navigate('login');
}
// Render any loading content that you like here
render() {
return (
<View style={styles.container}>
<ActivityIndicator />
</View>
);
}
}
const mapStateToProps = ({ settings }) => ({
isAuthenticated: state.profileInfo.isAuthenticated,
isLoaded: state.profileInfo.isLoaded,
googleProfileLoading: state.profileInfo.googleProfileLoading
});
export default connect(mapStateToProps)(InitialLoadingScreen);
As you can see, you can connect InitialLoadingScreen
to the redux store, to access any data and use it for your routing logic :)
So you have one redux state variable isAuthenticated
.
In every screen you'll need to check for this state, if not logged in then thow user to login screen and reset navigation stack.
you can check in any life cycle method which will be called on first run,
for e.g., constructor
, ponentWillMount
, ponentDidMount
, etc...
for redux state checking,
if(!this.props.isAuthenticated){
this.props.logoutAction();
this.props.navigation.navigate("Login");//Login or whatever your first screen is...
}
and for clearing whole stack,you'll need to create action which we called in above section.
export const logoutAction = () => {
return dispatch => dispatch({ type: LOGOUT_SUCCESS });
};
and you have to change some logic in file where you have written bine reducer's code,
const appReducer = bineReducers({
loginReducers: LoginReducers,
...
...
});
export default (rootReducer = (state, action) => {
if (action.type == LOGOUT_SUCCESS) {
state = undefined;
}
return appReducer(state, action);
});
this will reset whole reducer.
Now if you want to make logout button then onPress
of button just change isAuthenticated
to false
and fire navigate method and logout action that's all.
you can use react-native router flux for navigation
https://www.npmjs./package/react-native-router-flux
sample:
<Text
style={alerts.btn}
onPress={
() => Actions.question(
// send data
{
'code': data_1,
})}>
Go to Home
</Text>