Passing of variables assigned from one screen to another - react-native

basically I need to pass over a parameter called tempRole over from Login to MainTabNavigator and create tabs accordingly to user role. For example, vendor have 4 tabs and others just 3 tabs. However, I can't seem to get the role passed over though.
From Login
import React from 'react';
import { Text, View, StyleSheet, Platform, TextInput, TouchableOpacity } from 'react-native';
import firebase from 'firebase';
import { Container, Form, Item, Label, Input, Button } from "native-base";
import * as FirebaseAPI from '../modules/firebaseAPI';
import MainTabNavigator from '../navigation/MainTabNavigator';
import bottomTabNavigator from '../navigation/MainTabNavigator';
export default class LoginScreen extends React.Component {
constructor(props) {
super(props);
}
static navigationOptions = {
title: 'Login',
};
state = {
LoginEmail: "",
LoginPassword: "",
};
componentDidMount() {
this.watchAuthState(this.props.navigation)
try {
window = undefined;
} catch (e) {
}
}
watchAuthState(navigation) {
firebase.auth().onAuthStateChanged(function(user) {
console.log('onAuthStateChangedLOGIN: ', user)
if (user) {
// user.displayName will be like vendor.Peter
// e.g. role.name
var tempName = user.displayName;
navigation.navigate('Main', {
userRole: tempName.substr(0,tempName.indexOf('.'))
});
}
});
}
signIn(LoginEmail, LoginPassword) {
FirebaseAPI.signInUser(LoginEmail, LoginPassword);
}
render() {
return (
<Container style={styles.container}>
<Form>
<Text style={styles.text}>Login</Text>
<Item style={styles.standardDefaultInput} floatingLabel>
<Label style={{textAlign: 'center'}}>Email (example#example.com)</Label>
<Input
autoCapitalize="none"
style={{textAlign: 'center'}}
autoCorrect={false}
onChangeText={(text) => this.setState({LoginEmail: text})}
value={this.state.LoginEmail}
/>
</Item>
<Item style={styles.standardDefaultInput} floatingLabel>
<Label style={{textAlign: 'center'}}>Password (min. 6 charatcers)</Label>
<Input
autoCapitalize="none"
style={{textAlign: 'center'}}
autoCorrect={false}
onChangeText={(text) => this.setState({LoginPassword: text})}
value={this.state.Password}
/>
</Item>
<Button style={styles.standardDefaultButton} onPress={() => this.setState(this.signIn(this.state.LoginEmail, this.state.LoginPassword))} full rounded success>
<Text>Log In</Text>
</Button>
<Button style={styles.standardDefaultButton} onPress={() => this.props.navigation.navigate('SignUp')} full rounded link>
<Text>Sign Up</Text>
</Button>
</Form>
</Container>
);
};
}
Do take note that the navigation to Main is to the TabNavigator
From MainTabNavigator
let bottomTabNavigator = null
//let user = navigation.getParam(user)
//let userRole = user.displayName.substr(0,user.displayName.indexOf('.'))
//const { navigation } = this.props;
// The above failed
let userRole = navigation.getParam('userRole');
if (userRole == "vendor") {
bottomTabNavigator = createBottomTabNavigator({
HomeStack,
ListingStack,
CalendarStack,
ProfileStack
});
} else {
bottomTabNavigator = createBottomTabNavigator({
HomeStack,
CalendarStack,
ProfileStack
});
}
export default bottomTabNavigator

Use the global function to pass the value.
Global functions are useful when you need to pass data to a screen that is not a relationship between parents and children.
Global function Screen:
let NICKNAME = "";
function setNickName(data) {
NICKNAME = data;
}
function getNickName() {
return NICKNAME;
}
export {setNickName,getNickName }
senddata Screen:
import {setNickName} from "GlobalFunctionScreen"
...
this.state={
data: "sendData"
}
...
componentDidMount(){
setNickName(this.state.data);
}
receive data Screen:
import {getNickName} from "GlobalFunctionScreen"
...
componentDidMount(){
data = getNickName();
alert(data);
}

Related

React Native Redux - Not showing updated state via different route

I'm writing a react-native app via expo and trying to implement redux. I'm not sure if I'm going about this completely the wrong way. I have a home page that has two sections, a search text box and an area with links to content pages. The content pages also contain the same search box component. I want to be able to pass the contents of the search box input to the content page so that the user doesn't need to enter this again (and will probably require access to this content further in the user journey)
My app.js looks like the below:
import React from 'react';
import 'react-native-gesture-handler';
import { createStackNavigator } from 'react-navigation-stack';
import { createAppContainer } from 'react-navigation';
import ContentPage from './pages/ContentPage.js';
import LogoTitle from './components/LogoTitle';
import EventsListPage from './pages/EventsListPage.js';
import EventPage from './pages/EventPage';
import VenuePage from './pages/VenuePage';
import HomeScreen from './pages/HomePage';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
const initialState ={
postcode:"abcefg"
}
const reducer = (state = initialState, action) => {
switch(action.type)
{
case 'SET_POSTCODE':
return {
postcode: action.text
}
default:
console.log("returning default state")
return state
}
}
const store = createStore(reducer);
const RootStack = createStackNavigator(
{
Home: HomeScreen,
ContentPage: ContentPage,
EventsListPage: EventsListPage,
EventPage: EventPage,
VenuePage: VenuePage
},
{
initialRouteName: 'Home',
defaultNavigationOptions: {
headerTitle: () => <LogoTitle />,
headerLeft: () => null,
headerStyle: {
backgroundColor: '#ADD8E6'
}
},
}
);
const AppContainer = createAppContainer(RootStack);
export default class App extends React.Component {
render() {
return (
<Provider store={store}>
<AppContainer />
</Provider>);
}
}
Homepage.js:
import React from 'react';
import { StyleSheet, View } from 'react-native';
import SearchBox from '../components/SearchBox'
import TypeDrillDownArea from '../components/TypeDrillDownArea'
import 'react-native-gesture-handler';
class HomeScreen extends React.Component {
constructor(props) {
super(props);
state = {
};
}
render() {
return (
<View style={styles.container}>
<SearchBox navigation={this.props.navigation} eventTypeId=''/>
<TypeDrillDownArea navigation={this.props.navigation} />
</View>
);
}
}
export default HomeScreen
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'stretch'
},
});
Relevant searchbox.js:
render() {
return (
<ImageBackground source={topperBackground} style={{width: '100%'}}>
<View>
<View style={styles.row}>
<View>
<TextInput
value={this.props.postcode}
autoCapitalize="characters"
style={styles.inputBox}
placeholder="Enter Postcode"
onChangeText={(e) => this.props.setPostcode(e)}
/>
</View>
<View>
<TouchableOpacity
disabled={this.state.locationDisabled}
onPress={() => {
this.props.navigation.navigate('EventsListPage', {
navigation: this.props.navigation,
eventTypeId: this.state.eventTypeId,
locLongitude: this.state.location.coords.longitude,
locLatitude: this.state.location.coords.latitude,
});
}}>
<Image
style={styles.locationPin}
source={locationPin}
/>
</TouchableOpacity>
</View>
</View>
<View style={styles.searchButtonArea}>
<TouchableOpacity
onPress={() => {
console.log("postcode is: " + this.state.postcode)
this.props.navigation.navigate('EventsListPage', {
eventTypeId: this.state.eventTypeId,
postcode: this.props.postcode,
});
}}>
<Text style={styles.searchButton}>SEARCH</Text>
</TouchableOpacity>
</View>
</View>
</ImageBackground>);
}
}
export default connect(mapStateToProps, mapDispatchToProps)(SearchBox)
function mapStateToProps(state){
return {
postcode:state.postcode
}
}
function mapDispatchToProps(dispatch){
return{
setPostcode : (e) => dispatch({
type: 'SET_POSTCODE',
postcode : e
})
}
}
and finally relevant contentpage.js:
<View style={styles.container}>
<SearchBox navigation={this.props.navigation} eventTypeId={this.state.eventTypeId} />
<Image source={imageType(this.state.dataSource[0].eventTypeId)} style={styles.eventType} />
<Text style={styles.textToDisplay}>
{this.state.dataSource[0].eventTypeDescription}
</Text>
</View>
On load, the box is prepopulated with "abcefg" as expected. Changing the contents hits the reducer as expected. However when I navigate to a content page which loads the search box again the value is empty, regardless if I've changed the original state or not.
Am I missusing redux for what it's intended? Should I be doing this a different way?
For clarity below is the organisation of the components
In the reducer(), you are accessing action.text but in the dispatch(), you passed postcode value to postcode instead of text.

Unable to run react-navigation functions on customised back button in React native

The function I am not able to run is the navigation functions in my example it's
this.this.props.navigation.goBack()
My Login File is posted below but the part with the problem is the short snippet
The error I am getting is: TypeError: undefined is not an object (evaluating 'LogIn.props.navigation')
First failed Snippet
static navigationOptions = {
headerLeft: () => (
<Button
onPress={()=>this.props.navigation.goBack()}
title="cancel"
color={colors.black}
/>
),
};
LogIn.js
import React, { Component } from 'react';
import { PropTypes } from 'prop-types';
import Icon from 'react-native-vector-icons/FontAwesome';
import colors from '../styles/colors';
import {
View,
Text,
ScrollView,
StyleSheet,
KeyboardAvoidingView,
Button
} from 'react-native';
import InputField from '../components/form/InputField';
import NexArrowButton from '../components/buttons/NextArrowButton';
import Notification from '../components/Notification';
export default class LogIn extends Component{
constructor(props){
super(props);
this.state ={
formValid:false,
validEmail:false,
emailAddress:'',
validPassword:false,
}
this.handleNextButton = this.handleNextButton.bind(this)
this.handleCloseNotification = this.handleCloseNotification.bind(this)
this.handleEmailChange = this.handleEmailChange.bind(this);
}
static navigationOptions = {
headerLeft: () => (
<Button
onPress={()=>this.props.navigation.goBack()}
title="cancel"
color={colors.black}
/>
),
};
handleNextButton(){
if(this.state.emailAddress === 'admin#mail.com'){
this.setState({formValid:true})
} else{
this.setState({formValid: false});
}
}
handleCloseNotification(){
this.setState({formValid:true });
}
handleEmailChange(email){
const emailCheckRegex = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
const { validEmail } = this.state;
this.setState({ emailAddress: email });
if (!validEmail) {
if (emailCheckRegex.test(email)) {
this.setState({ validEmail: true });
}
} else if (!emailCheckRegex.test(email)) {
this.setState({ validEmail: false });
}
}
handlePasswordChange(password){
const { validPassword } = this.state;
this.setState({ password });
if (!validPassword) {
if (password.length > 4) {
// Password has to be at least 4 characters long
this.setState({ validPassword: true });
}
} else if (password <= 4) {
this.setState({ validPassword: false });
}
}
render(){
const {formValid, validPassword} = this.state;
const showNotification = formValid ? false:true;
const background = formValid ? colors.green01 : colors.darkOrange;
const notificationMarginTop = showNotification ? 10:0;
return(
<KeyboardAvoidingView style={[{backgroundColor:background}, styles.wrapper] } behavior="padding">
<View style={styles.ScrollViewWrapper}>
<ScrollView style={styles.ScrollView}>
<Text style={styles.loginHeader}>Log In</Text>
<InputField
labelText= "Email Address"
labelTextSize={20}
labelColor={colors.white}
textColor={colors.white}
borderBottomColor={colors.white}
inputType="email"
customStyle={{marginBottom:30}}
onChangeText={this.handleEmailChange}
/>
<InputField
labelText= "Password"
labelTextSize={20}
labelColor={colors.white}
textColor={colors.white}
borderBottomColor={colors.white}
inputType="password"
customStyle={{marginBottom:30}}
/>
</ScrollView>
<View style={styles.nextButton}>
<NexArrowButton
// handleNextButton={this.handleNextButton}
handleNextButton={()=>this.props.navigation.goBack()}
/>
</View>
<View style={[styles.notificationWrapper, {marginTop:notificationMarginTop}]}>
<Notification
showNotification={showNotification}
handleCloseNotification={this.handleCloseNotification}
type="Error"
firstLine="Those credentials don't look right."
secondLine="Please try again."
/>
</View>
</View>
</KeyboardAvoidingView>
)
}
}
const styles = StyleSheet.create({
wrapper:{
display:'flex',
flex:1,
},
ScrollViewWrapper:{
marginTop:60,
flex:1,
},
ScrollView:{
paddingLeft:30,
paddingRight:30,
paddingTop:10,
flex:1,
},
loginHeader:{
fontSize:34,
color:colors.white,
fontWeight:'300',
marginBottom:40,
},
nextButton:{
position:'absolute',
right:20,
bottom:20,
},
notificationWrapper:{
position: 'absolute',
bottom:0,
zIndex:9
}
});
The most confusing part is that the second snippet below of Login.js works perfectly and it is essentially the same thing which means that I am getting the props right, but still get the error in customised back button.
Second working snippet
<View style={styles.nextButton}>
<NexArrowButton
// handleNextButton={this.handleNextButton}
handleNextButton={()=>this.props.navigation.goBack()}
/>
</View>
App.js
import React, { Component } from 'react';
import { Platform, StyleSheet, Text, View } from 'react-native';
import LoggedOut from './src/screens/LoggedOut';
import LogIn from './src/screens/LogIn';
import LoggedIn from './src/screens/LoggedIn';
import {createAppContainer} from 'react-navigation';
import {createStackNavigator} from 'react-navigation-stack';
const RootStack = createStackNavigator(
{
LoggedOut: LoggedOut,
LogIn: LogIn,
},
{
initialRouteName: 'LoggedOut',
}
);
const AppContainer = createAppContainer(RootStack);
export default class App extends React.Component {
render() {
return <AppContainer />;
}
}
The error in more details
I really appreciate your help ! I am happy to provide more code if it makes it easier to debugg.
You have to change the static navigationOptions to following snippet if you want to access navigation properties in a static function:
static navigationOptions = ({ navigation }) => ({
headerLeft: () => (
<Button
onPress={()=>navigation.goBack()}
title="cancel"
color={colors.black}
/>
),
});
You don't need the this.props in this case ;) The static function does not have access to the this context so this.props will not work.

How to set initial state empty when try to navigation to other page react native

I have a problem when i try to navigation.navigate called RegisterPage but before that i try to typing anycharacter in field email and after that i click register button and back again, but the field is not empty
LoginContainer.js
import React, { Component, Fragment } from 'react';
import LoginComponent from '../../modules/LoginComponent/component/LoginComponent';
import axios from 'axios';
import { Toast } from '#ant-design/react-native';
class LoginContainer extends Component {
static navigationOptions = {
header: null,
}
constructor(props) {
super(props);
this.state = {
post : [],
email : '',
password : '' ,
showPassword: true,
}
}
onValueChange = (text, name) => {
this.setState({
[name] : text
});
}
getPostAPI = () => {
axios.get('http://10.2.62.212:3000/dataadmin')
.then((res) => {
this.setState ({
post : res.data,
})
})
.catch((err) => {
})
}
showPassword = () => {
const showPassword = !this.state.showPassword
this.setState({ showPassword });
}
onLoginPress = (event) => {
event.preventDefault();
const { post } = this.state;
if(!this.state.email.trim()) {
Toast.fail('Invalid Email', 1, undefined, false)
} else
if(!this.state.password.trim()) {
Toast.fail('Invalid Password', 1, undefined, false)
} else
if (post.find(e => `${e.email}${e.password}` === `${this.state.email}${this.state.password}` )) {
this.props.navigation.navigate('Dashboard');
} else
if (post.find(e => `${e.email}${e.password}` !== `${this.state.email}${this.state.password}` )) {
Toast.fail('Invalid Email or Password', 1, undefined, false)
}
}
onRegistPress = () => {
this.props.navigation.navigate('Register')
}
componentDidMount() {
this.getPostAPI();
}
render() {
return (
<Fragment>
<LoginComponent
navigation = {this.props.navigation}
change = {this.props.change}
onValueChange={this.onValueChange}
showPassword={this.showPassword}
onLoginPress={this.onLoginPress}
showPassword={this.state.showPassword}
onRegistPress = {this.onRegistPress}
/>
</Fragment>
);
}
}
export default LoginContainer;
LoginComponent.js
import React from 'react';
import { View, Text, TextInput, TouchableOpacity } from 'react-native';
import PropTypes from 'prop-types';
import { Button, Icon, Provider } from '#ant-design/react-native';
import styles from '../../../../assets/styles/default.style'
class LoginComponent extends React.Component {
static navigationOptions = {
header: null,
}
render() {
return (
<Provider >
<View style={styles.containerLogin}>
<View style={styles.parentViewStyleLogin}>
<Text style={styles.textHeaderStyle}> Merchant APP </Text>
<Text style={styles.textStyle}>Email</Text>
<View style={styles.inputContainer}>
<Icon style = {styles.styleIcon} name={"user"} color='black'/>
<TextInput
style={styles.textboxfield}
underlineColorAndroid='transparent'
onChangeText={(text) => this.props.onValueChange(text, 'email')}
placeholder = {'Input your email here'}
placeholderTextColor={'rgba(221,221,221,1)'}
/>
</View>
<Text style={[styles.textStyle, {marginTop: 20}] }> Password </Text>
<View style={styles.inputContainer}>
<Icon style = {styles.styleIcon} name={"key"} color='black'/>
<TextInput
style={styles.textboxfield}
secureTextEntry={this.props.showPassword}
underlineColorAndroid='transparent'
onChangeText={(text) => this.props.onValueChange(text, 'password')}
returnKeyType={'done'}
placeholder = {'Input your password here'}
placeholderTextColor={'rgba(221,221,221,1)'}
/>
</View>
<TouchableOpacity >
<Button style={[styles.buttonTextStyle, { borderRadius : 30 }]} onPress = {this.props.onLoginPress} >Login</Button>
</TouchableOpacity>
<TouchableOpacity onPress = {() => this.props.onRegistPress()} >
<Text style={styles.textDefault} >Dont have account ? Register</Text>
</TouchableOpacity>
</View>
</View>
</Provider>
);
}
}
export default LoginComponent
navigation
import { createStackNavigator } from 'react-navigation-stack';
import { createAppContainer } from 'react-navigation';
import LoginContainer from '../../app/LoginContainer/LoginContainer';
import DashboardContainer from '../../app/DashboardContainer/DashboardContainer';
import NotificationContainer from '../../app/NotificationContainer/NotificationContainer';
import TransactionContainer from '../../app/TransactionContainer/TransactionContainer'
import RegisterContainer from '../../app/RegisterContainer/RegisterContainer'
import DetailContainer from '../../app/DetailContainer/DetailContainer';
const AppNavigator = createStackNavigator(
{
Login: { screen: LoginContainer },
Dashboard: { screen: DashboardContainer },
Notification: { screen: NotificationContainer },
Transaction : { screen: TransactionContainer },
Register : { screen : RegisterContainer },
Detail : { screen : DetailContainer }
},
);
export default createAppContainer(AppNavigator);
this my ui
look after i try to type anycharacter and then directly click signup , and then click sigin again , and the field is not empty. i dont know how to fix it
there are 2 ways you can achieve this :
While you click on register in the DOnt have account text , then before navigation.navigate you can set the state of email to '' , like
onRegisterClick = () =>{
this.setSTate({email:''});//first this
this.props.navigation.navigate('Register');//then this
}
You can go back to the login page again by this.props.navigation.push('Login') rahther than navigation.navigate coz what navigate does is it calls the page from existing stack ,and push creates a new stack so values will be reset , so email will be null

How to jump another page after login/sign up

I build navigation with react-navigation v3 and auth with firebase. No problem with that. Navigation flow is works and I can sign up. The problem I am facing is, when I push the Sign up button it doesn't jump to Signup Screen.
So the structure that Build: in App.js I am doing navigation part. First sending Welcome Screen which include Login.
This is Welcome Screen:
import React, { Component } from 'react'
import {StyleSheet, View } from "react-native";
import {Container, Text, Form, Content, Header, Button, Input, Label, Item} from 'native-base';
import SignUp from '../screens/register/SignUp'
import * as firebase from 'firebase';
const firebaseConfig = {
apiKey: "example example",
authDomain: "example example",
databaseURL: "example example",
projectId: "example example",
storageBucket: "example example",
};
firebase.initializeApp(firebaseConfig);
export default class WelcomeScreen extends Component {
constructor(props){
super(props)
this.state = ({
email: '',
password: ''
})
}
loginUser = (email, password, navigate) => {
try {
firebase.auth().signInWithEmailAndPassword(email,password).then(function(user){
console.log(user);
navigate('Learn')
})
}
catch (error) {
console.log(error.toString())
}
};
render() {
return (
<Container style={styles.container}>
<Form>
<Item floatingLabel>
<Label>E-mail</Label>
<Input
autocorrect={false}
autoCapitalize={'none'}
onChangeText={(email) => this.setState({email})}
/>
</Item>
<Item floatingLabel>
<Label>Password</Label>
<Input
secureTextEntry={true}
autocorrect={false}
autoCapitalize={'none'}
onChangeText={(password)=>this.setState({password})}
/>
</Item>
</Form>
<Button style={{backgroundColor:'#6c5ce7', marginTop: 10}}
onPress={()=>this.loginUser(this.state.email,this.state.password)}
rounded
success
>
<Text>Kelimeda'ya Uç</Text>
</Button>
<Button style={{backgroundColor:'#6c5ce7', marginTop: 10}}
onPress={()=>this.props.navigation.navigate('SignUp')}
rounded
primary
>
<Text>Beni Kaydet!</Text>
</Button>
</Container>
);
}
}
Sign Up Screen:
import React, { Component } from 'react'
import {StyleSheet, View } from "react-native";
import {Container, Text, Form, Content, Header, Button, Input, Label, Item} from 'native-base';
import * as firebase from 'firebase';
export default class WelcomeScreen extends Component {
constructor(props){
super(props)
this.state = ({
email: '',
password: ''
})
}
signUpUser = (email, password) => {
try {
if(this.state.password.length < 6){
alert('Lutfen 6 dan daha uzun bir karakter giriniz.')
return
}
firebase.auth().createUserWithEmailAndPassword(email,password)
}
catch (error) {
console.log(error.toString())
}
};
render() {
return (
<Container style={styles.container}>
<Form>
<Item floatingLabel>
<Label>E-mail</Label>
<Input
autocorrect={false}
autoCapitalize={'none'}
onChangeText={(email) => this.setState({email})}
/>
</Item>
<Item floatingLabel>
<Label>Password</Label>
<Input
secureTextEntry={true}
autocorrect={false}
autoCapitalize={'none'}
onChangeText={(password)=>this.setState({password})}
/>
</Item>
</Form>
<Button style={{backgroundColor:'#6c5ce7', marginTop: 10}}
onPress={()=>this.signUpUser(this.state.email,this.state.password)}
rounded
primary
>
<Text>Beni Kaydet!</Text>
</Button>
</Container>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 5,
justifyContent: 'center',
backgroundColor: '#fff',
},
});
and this is the App Screen. Do I need to check here user Logged in or Not? or Welcome Screen?
//imports...
import React, { Component } from 'react';
import {View, StatusBar} from 'react-native';
import {
createSwitchNavigator,
createAppContainer,
createDrawerNavigator,
createBottomTabNavigator,
createStackNavigator,} from 'react-navigation';
import Icon from 'react-native-vector-icons/Ionicons';
import WelcomeScreen from './src/screens/Welcome';
import Learn from './src/screens/Tab/Learn';
import Settings from './src/screens/Tab/Settings';
import Play from './src/screens/Tab/Play';
//content: const & functions and styles...
const DashboardTabNavigator = createBottomTabNavigator({
Play,
Learn,
Settings
},
{
navigationOptions: ({navigation}) => {
const {routeName} = navigation.state.routes
[navigation.state.index];
return {
headerTitle: routeName,
headerTintColor:'#fff',
headerStyle:{
backgroundColor: '#2c3e50',
}
};
}
});
const DashStack = createStackNavigator({
DashboardTabNavigator: DashboardTabNavigator
}, {
defaultNavigationOptions:({navigation}) =>{
return {
headerLeft: <Icon
style={{paddingLeft: 15, color:'#fff'}}
onPress={()=>navigation.openDrawer()}
name={'md-menu'}
size={30}
/>
}
},
});
const appDrawNavigator = createDrawerNavigator({
Dashboard:{ screen: DashStack }
});
const appSwitchNavigation = createSwitchNavigator({
Welcome:{ screen: WelcomeScreen },
Dashboard:{ screen: appDrawNavigator }
});
const AppContainer = createAppContainer(appSwitchNavigation);
class App extends Component {
render() {
return(
<View style={{flex: 1}}>
<StatusBar
backgroundColor="blue"
barStyle="light-content"
/>
<AppContainer/>
</View>
) ;
}
}
export default App;
Your login function looks like this:
loginUser = (email, password, navigate) => {
try {
firebase.auth().signInWithEmailAndPassword(email,password).then(function(user){
console.log(user);
navigate('Learn')
})
}
catch (error) {
console.log(error.toString())
}
};
This function expecting three parameters. You should pass this.props.navigation.navigate to the login function to use navigate('Learn')
<Button
style={{backgroundColor:'#6c5ce7', marginTop: 10}}
onPress={()=>this.loginUser(this.state.email,this.state.password,this.props.navigation.navigate)}
rounded
success
>
Solution for problem 1: You have not passed navigate to your loginUser function, so it is not working. Please send the navigate param to the loginUser like this.
<Button
style={{backgroundColor:'#6c5ce7', marginTop: 10}}
onPress={()=>this.loginUser(this.state.email,this.state.password, this.props.navigation.navigate)}
rounded
success>
Solution for problem 2: For the firebase duplication issue, its because you are initialising the firebase instance twice in the application. What you should do instead is, just initialize the firebase at the application root component like App.js or Splash screen, so that it can be available throughout the app lifecycle and whenever you need to use it just import it and use.
Solution for problem 3: Its a common usecase as to know the logged in status of the user upfront to navigate the user appropriately into the application.
For this, what you can do is, just save a flag in AsyncStorage for eg. isLoggedIn as YES upon successful login, and post this, whenever the app is opened just analyse with the flag's presence/value wether the user is logged in or not. A good place to do this is either your app's Splashscreen component or the root component of the application.
Edited Answer (additional): (for problem 1)
You have your navigation routes nested wrongly to directly jump to Learn from
welcome screen, to navigate from one screen to another, the two screen should be in same navigation scope (if navigator is given as a route in another navigator then the route navigator is considered as a screen and the user will be navigated to its initial route when navigated to it)
Your code should target navigating to Dashboard route, which will internally render the nested navigators i.e. the first/initial route but with current nesting this will land you to Play so what can be done is, make Learn as first/initial route of your tab navigator.
The code in the loginUser should be navigate('Dashboard') and your tab navigator should have Learn as its initial route.

react navigation navigate to other screen

i try make login, when isLoggedIn = true then navigate to Profile, but always give me error
undefined is not an object (evaluating '_this.props.navigation')
whats wrong with mycode? can someone help me?
import React from 'react'
import {
Image,
StyleSheet,
Text,
TextInput,
TouchableOpacity,
View
} from 'react-native'
import { Field, reduxForm } from 'redux-form'
import { Container, Content, InputGroup, Button , Input, Icon, Item } from 'native-base';
import { login } from '../Action/Action';
import {NavigationActions} from "react-navigation";
import styles from './Style';
import { connect, } from 'react-redux'
}
function submit(values) {
console.log(values);
}
const renderInput = ({ input: { onChange, ...restInput }}) => {
return <Input onChangeText={onChange} {...restInput} />
}
}
const Form = props => {
//const {navigate} = this.props.navigation;
//let _navigateTo;
if (props.appUser.isLoggedIn) {
console.log("haloooo");
const navigateAction = NavigationActions.navigate({
routeName: 'Profile',
params: {},
action: NavigationActions.navigate({ routeName: 'SubProfileRoute'})
})
this.props.navigation.dispatch(navigateAction)
}
const { handleSubmit } = props
//console.log(props.appUser);
return (
<Container >
<Content>
<Content>
<View style={styles.container}>
<Image source={require('../Assets/Octocat.png')} style={{width: 128, height: 128}} />
</View>
</Content>
<Content style={{paddingLeft:10,paddingRight:10,paddingBottom:5, paddingTop:30}}>
<Item rounded>
<Field name="username" component={renderInput} />
</Item>
</Content>
<Content style={{paddingLeft:10,paddingRight:10}}>
<Item rounded>
<Field name="password" component={renderInput} />
</Item>
</Content>
<Content style={{padding:10}}>
<Button onPress={handleSubmit(props.onLogin)} block info>
<Text>Login</Text>
</Button>
</Content>
</Content>
</Container>
)
}
const myReduxForm = reduxForm({
form: 'MyReduxForm',
})(Form)
function mapStateToProps(state) {
return {
appUser: state.appUser,
}
}
function mapDispatchToProps(dispatch) {
return {
onLogin: (data) => { dispatch(login(data)); },
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(myReduxForm)
// export default reduxForm({
// form: 'test'
// })(Form)
// export default reduxForm({
// form: 'test'
// })(Form)
try to use withNavigation. Use the component FormWithNavigation as shown in the code below
const Form = ({ navigation }) => {
//..
navigation.navigate('XXX')
}
const FormWithNavigation = withNavigation(Form);
you use this.props instead just props
this one should work
const { handleSubmit, navigation: {navigate} } = props