React Native: How can I redirect after login to different pages depending on the type of account of a user? - react-native

I'm building a react native app using expo and I would like to know how I can send a "UserTypeA" to Homepage and send a "UserTypeB" to Profile upon login.
I have a UserTypeA tab navigator and a UserTypeB tab navigator, with just 2 pages that will be see able by both accounts.
I have my UserTypeA data and UserTypeB data in separate tables so I can identify which user has which type.
Sorry if it's not clear this is my first question.
Thank you for your help!

In your apps main render method, you could do something like this.
Basically, you will listen to your redux state and switch main screen depending on the user type.
class MyApp extends PureComponent {
constructor(props) {
super(props);
}
render() {
const { auth } = this.props;
if (auth.userObj.type1) {
return <Type1MainComponent />;
}
if (auth.userObj.type2) {
return <Type2MainComponent />;
}
return <LoginScreen />;
}
}
function mapStateToProps(state) {
const { auth } = state;
return { auth };
}
export default connect(mapStateToProps)(MyApp);

Related

Passing props to components in React Navigation v5 dynamic component configuration

In my app, I am displaying a login screen if the user is not logged in, and a logged-in screen if the user is logged in. In the simple example below, you can see that I am checking if the jwt and user exists in my redux store and then displaying the appropriate screen.
type Props = {
+jwt: string | null;
+user: UserModel | null;
};
export class AuthStackNavigator extends Component<Props> {
renderScreen() {
if (this.props.jwt && this.props.user) {
return (
<Stack.Screen name={'AuthenticatedView'} component={AuthenticatedView} />
);
} else {
return (
<Stack.Screen name={'LoginView'} component={LoginView} />
);
}
}
render() {
return (
<Stack.Navigator>
{this.renderScreen()}
</Stack.Navigator>
);
}
}
const mapStateToProps = (state) => {
return {
jwt: getJwt(state),
user: getUser(state)
};
};
export default connect(mapStateToProps)(AuthStackNavigator);
You can see that the AuthenticatedView component is rendered if the jwt and user exists. Inside AuthenticatedView, I am currently getting the user from the redux store again where it is possibly null - this involves another check. Is there a way I can pass the user to the component as a prop from <Stack.Screen> as I know it exists here? This way I do not have to make the same check multiple times.
I'm aware that you can send data to components when navigating using:navigation.navigate('View', props), but I do not navigate to this screen using this function.
Read the official documentation https://reactnavigation.org/docs/hello-react-navigation/#passing-additional-props

How to show login page instead of home page

I'm using the default bottom tab navigation app from the expo example
My appnavigator.js looks like this
export default createAppContainer(createSwitchNavigator({
// You could add another route here for authentication.
// Read more at https://reactnavigation.org/docs/en/auth-flow.html
Main: MainTabNavigator,
}));
I want to check if the user is logged in, by checking the asyncstorage loginname value. In the home.js, if there is no loginname, then I want to redirect to the sigin.js page.
I suggest creating a file called initializing.js as a screen, which will be the first entry point in the app and put the logic there.
export default class Initializing extends Component {
async componentDidMount() {
try {
const token = await AsyncStorage.getItem('user_token');
const skipOnBoarding = true;
const authenticated = true;
if (token) await goToHome(skipOnBoarding, authenticated);
else await goToAuth();
SplashScreen.hide();
} catch (err) {
await goToAuth();
SplashScreen.hide();
}
}
render() {
return <View />;
}
}
I worked it out. was very easy.
First do this in the appNavigator.js
import SignIn from '../screens/SignIn'
export default createAppContainer(createSwitchNavigator({
// You could add another route here for authentication.
// Read more at https://reactnavigation.org/docs/en/auth-flow.html
Main: MainTabNavigator,
SignIn: SignIn // signIn is the login page
}));
Next, at the logic where you check for user logined do something like this.
AsyncStorage.getItem('loginname').then((value) => {
console.log(value)
this.props.navigation.navigate('SignIn')
})
the prop this.props.navigation.navigate is automatically avaiable in every stack, you dont need to pass it around to use it

Changing state in React native App.js from another component

I'm making authentication in an app, and I'm kind of stuck. I have 2 different navigations. One shows if the user is logged in and another one if not. Basically, a Sign in screen. It's working fine if I change the value manually upon the start. But I can't find a way to change a state when a user signs in, for example. Even though the value in auth module changes, it doesn't update in App.js So how can I update the App.js's state from Sign in screen, for example?
import React, { Component } from 'react';
import { AppRegistry, Platform, StyleSheet, Text, View } from 'react-native';
import DrawerNavigator from './components/DrawerNavigator'
import SignedOutNavigator from './components/SignedOutNavigator'
import auth from './auth'
type Props = {};
export default class App extends Component<Props> {
constructor(props) {
super(props)
this.state = {
isLoggedIn: auth.isLoggedIn
}
}
render() {
return (
(this.state.isLoggedIn) ? <DrawerNavigator /> : <SignedOutNavigator />
);
}
}
AppRegistry.registerComponent('App', () => App)
and my auth module, which is very simple
import { AsyncStorage } from 'react-native';
// try to read from a local file
let api_key
let isLoggedIn = false
function save_user_settings(settings) {
AsyncStorage.mergeItem('user', JSON.stringify(settings), () => {
AsyncStorage.getItem('user', (err, result) => {
isLoggedIn = result.isLoggedIn
api_key = result.api_key
});
isLoggedIn = true
});
}
module.exports.save_user_settings = save_user_settings
module.exports.api_key = api_key
module.exports.isLoggedIn = isLoggedIn
First off, there are loads of ways to approach this problem. Because of this I'm going to try explain to you why what you have now isn't working.
The reason this is happening is because when you assign auth.isLoggedIn to your isLoggedIn state, you are assigning the value once, kind of as a copy. It's not a reference that is stored.
In addition to this, remember, React state is generally only updated with setState(), and that is never being called here, so your state will not update.
The way I would approach this problem without bringing in elements like Redux, which is overkill for this problem by itself, is to look into building an authentication higher order component which handles all the authentication logic and wraps your entire application. From there you can control if you should render the children, or do a redirect.
Auth Component
componentDidMount() {
this._saveUserSettings(settings);
}
_saveUserSettings(settings) {
AsyncStorage.mergeItem('user', JSON.stringify(settings), () => {
AsyncStorage.getItem('user', (err, result) => {
isLoggedIn = result.isLoggedIn
api_key = result.api_key
});
this.setState({isLoggedIn: true});
});
}
render() {
const { isLoggedIn } = this.state;
return isLoggedIn ? this.props.children : null;
}
App.js
render() {
<AuthComponent>
//the rest of authenticated app goes here
</AuthComponent>
}
Here's a really quick, incomplete example. But it should showcase to you how you may want to lay your authentication out. You'll also want to consider error handling and such, however.

My screen names aren't appearing in Firebase Analytics Dashboard

I am trying to track screen names on react-native-firebase in conjunction with react-navigation.
Here is my code.
const tracker = firebase.analytics()
function getCurrentRouteName(navigationState) {
if (!navigationState) {
return null;
}
const route = navigationState.routes[navigationState.index];
// dive into nested navigators
if (route.routes) {
return getCurrentRouteName(route);
}
return route.routeName;
}
export default class AppNavigation extends Component {
render() {
StatusBar.setBarStyle('light-content');
return (
<MainScreenNavigator
onNavigationStateChange={(prevState, currentState) => {
const currentScreen = getCurrentRouteName(currentState);
const prevScreen = getCurrentRouteName(prevState);
if (prevScreen !== currentScreen) {
// the line below uses the Google Analytics tracker
// change the tracker here to use other Mobile analytics SDK.
tracker.setCurrentScreen(currentScreen);
}
}}
/>
);
}
}
When I console log the screen names, they appear as desired. However, I'm not seeing the results in Firebase console. When I filter screen by name it just says (not set). Am I doing something wrong in my code? I am importing firebase from 'react-native-firebase' as well.
The code above is solid. It turns out you have to wait a half a day or so before data is populated. Not sure if I missed that in the docs. If you're using react-navigation and firebase, this code works!

how to call a function on page refresh in react-redux?

Iam doing an app in react-redux and i want to hold my redux store on page refresh and thought to not make use of predefined libraries and hence i set the redux state to local state and making the api call in componentWillUnmount to restore redux state on page refresh.But i couldnt do that. Is their any approch to acheive this:
And my code is:
componentWillMount(){
this.setState({
activeUser:this.props.activeUser
})
}
componentWillUnmount(){
this.props.loginUser(this.state.activeUser.user);
}
activeUser is my redux state and this.props.loginUser() makes api call.And i tried of using event handlers as:
componentDidMount(){
window.addEventListener('onbeforeunload', this.saveStore)
}
componentWillUnmount(){
window.removeEventListener('beforeunload', this.saveStore)
}
saveStore(){
this.props.loginUser(this.state.activeUser.user);
}
but it didn't worked for me.
My understanding is that what you basically are trying to do is that, you want to persist your app state (user info, etc) between reloads.
One can use the localStorage API to achieve this effect.
I'll give one possible solution down here.
class App extends React.Component {
constructor(props) {
super(props);
this.state = {activeUser: null};
}
componentWillMount() {
let activeUser = localStrorage.getItem("activeUser");
if (activeUser) {
this.props.receivedActiveUser(JSON.parse(activeUser));
}
}
componentWillReceiveProps(nextProps) {
this.setState({activeUser: nextProps.activeUser});
}
componentWillUnmount(){
if (this.state.activeUser) {
localStorage.setItem("activeUser", JSON.stringify(this.state.activeUser));
}
}
}
Ofcourse, you'll have to create a receivedActiveUser action which will update the store appropriately.