React Native show Dialog or Popup in catch error handler - javascript

I am very new to React Native and try to show a popup if an error ist throwen. But I dont get it to work. Thats my code:
import React, { useState, useEffect } from 'react'
import { Alert, Modal, TouchableOpacity, StyleSheet, View, Pressable } from 'react-native'
import { Text } from 'react-native-paper'
import Background from '../components/Background'
import Logo from '../components/Logo'
import Header from '../components/Header'
import Button from '../components/Button'
import TextInput from '../components/TextInput'
import BackButton from '../components/BackButton'
import { theme } from '../core/theme'
import { emailValidator } from '../helpers/emailValidator'
import { passwordValidator } from '../helpers/passwordValidator'
import Icon from 'react-native-vector-icons/FontAwesome5';
export default function LoginScreen({ navigation }) {
const [email, setEmail] = useState({ value: '', error: '' })
const [password, setPassword] = useState({ value: '', error: '' })
const [hidePass, setHidePass] = useState(true);
const onLoginPressed = () => {
const emailError = emailValidator(email.value)
const passwordError = passwordValidator(password.value)
if (emailError || passwordError) {
setEmail({ ...email, error: emailError })
setPassword({ ...password, error: passwordError })
return
}else{
const SignUp = async () => {
try {
const response = await fetch('https://www.ecample.com/endpoint', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: email.value,
password: password.value
})
})
let json = await response.json()
if ((typeof json.token !== 'undefined') && (json.token.length > 230)) {
alert('fdgdg')
} else {
navigation.reset({
index: 0,
routes: [{ name: 'ErrorPage' }],
})
}
} catch (err) {
console.log(err)
return (
<View style={styles.centeredView}>
<Modal
animationType="slide"
transparent={true}
visible={modalVisible}
onRequestClose={() => {
Alert.alert("Modal has been closed.");
setModalVisible(!modalVisible);
}}
>
<View style={styles.centeredView}>
<View style={styles.modalView}>
<Text style={styles.modalText}>Hello World!</Text>
<Pressable
style={[styles.button, styles.buttonClose]}
onPress={() => setModalVisible(!modalVisible)}
>
<Text style={styles.textStyle}>Hide Modal</Text>
</Pressable>
</View>
</View>
</Modal>
<Pressable
style={[styles.button, styles.buttonOpen]}
onPress={() => setModalVisible(true)}
>
<Text style={styles.textStyle}>Show Modal</Text>
</Pressable>
</View>
);
}
}
} // ende else
}
return (
<Background>
<BackButton goBack={navigation.goBack} />
<Logo />
<Header>Bitte geben Sie Ihre Daten ein.</Header>
<TextInput
label="E-Mail"
returnKeyType="next"
value={email.value}
onChangeText={(text) => setEmail({ value: text, error: '' })}
error={!!email.error}
errorText={email.error}
autoCapitalize="none"
autoCompleteType="email"
textContentType="emailAddress"
keyboardType="email-address"
/>
<TextInput
label="Passwort"
returnKeyType="done"
value={password.value}
onChangeText={(text) => setPassword({ value: text, error: '' })}
error={!!password.error}
errorText={password.error}
secureTextEntry={hidePass ? true : false}
/>
<Icon style={styles.eyeContainer}
name={hidePass ? 'eye-slash' : 'eye'}
size={15}
color="grey"
onPress={() => setHidePass(!hidePass)}
/>
<View style={styles.forgotPassword}>
<TouchableOpacity
onPress={() => navigation.navigate('ResetPasswordScreen')}
>
<Text style={styles.forgot}>Passwort vergessen?</Text>
</TouchableOpacity>
</View>
<Button color="#1584a5" mode="contained" onPress={onLoginPressed}>
Login
</Button>
<View style={styles.row}>
<Text>Keinen Account? </Text>
<TouchableOpacity onPress={() => navigation.replace('RegisterScreen')}>
<Text style={styles.link}>Jetzt registrieren</Text>
</TouchableOpacity>
</View>
</Background>
)
}
I tried different modules and scripts but I cant get a popup. The endpoint works fine. I receive a token, an error 403 or an html with 503 as answer. Therefore I used the catch error.
I nearly tried every Modal, Popup, Alert which I could find in the Internet.

You can use Alert component from react-native.
fetchEvents() {
fetch('http://www.wrongurl.com', {
method: 'GET',
redirect: 'follow'
})
.then(function(response) {
if (response.status == 200) {
let responseText = JSON.stringify(response.text());
console.log(responseText);
}
else throw new Error('HTTP response status not code 200 as expected.');
})
.catch(function(error) {
Alert.alert(error); // Using this line
});
}

const SignUp = async () => {
try {
const response = await fetch('https://www.example.com/endpoint', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: email.value,
password: password.value
})
})
if (response.status === 200) {
let json = await response.json()
if ((typeof json.token !== 'undefined') && (json.token.length > 230)) {
alert('fdgdg')
} else {
navigation.reset({
index: 0,
routes: [{ name: 'ErrorPage' }],
})
}
} else {
throw new Error(`failed due to status code ${response.status}`);
}
} catch (err) {
console.log(err)
// write code to open modal here
//openErrorModal(err)
}
}

Related

How can i fix this error LOG [TypeError: null is not an object (evaluating 'JSON.parse(value).token')]

Does anyone knows how can i fix this error? the error clearly says that LOG [TypeError: null is not an object (evaluating 'JSON.parse(value).token')] but i dont know what went wrong , Can anyone check my code and tell me what i did wrong? i checked my code spellings but i can't find my problem my backend is also running
import { StyleSheet, View, StatusBar, Text, Image, ActivityIndicator } from 'react-native';
import React, { useEffect, useState } from 'react';
import ButtomNavbar from '../../Components/ButtomNavbar';
import TopNavbar from '../../Components/TopNavbar';
import { formHead } from '../../CommonCss/FormCss';
import { ScrollView } from 'react-native-gesture-handler';
import defaultprofileimg from '../../../assets/profileimg.jpg';
import AsyncStorage from '#react-native-async-storage/async-storage';
const Profile = ({ navigation }) => {
const [userdata, setUserdata] = useState(null)
useEffect(() => {
AsyncStorage.getItem('user')
.then(async (value) => {
fetch('http://10.0.2.2:3000/userdata', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization' : 'Bearer' + JSON.parse(value).token
},
body: JSON.stringify({ email: JSON.parse(value).user.email })
})
.then(res => res.json()).then(data => {
if (data.message == 'User Data Fetched Susscessfully') {
setUserdata(data.user)
}
else {
alert('Something went wrong')
navigation.navigate('login')
}
})
.catch(err => {
alert(err)
console.log(err)
})
})
.catch(err => {
alert(err)
console.log(err)
})
}, [])
console.log(userdata)
return (
<View style={styles.container}>
<StatusBar />
<ButtomNavbar navigation={navigation} page={'profile'} />
<TopNavbar navigation={navigation} page={'profile'} />
{
userdata? <ScrollView>
<View style={styles.section1}>
{
userdata.profileImg.length>0 ?
<Image style={styles.profileimg} source={{ uri: userdata.profileImg}} />
:
<Image style={styles.profileimg} source={defaultprofileimg} />
}
<Text style={styles.usernameText}>#{userdata.username}</Text>
<View style={styles.Postrow}>
<View style={styles.Postrow1}>
<Text style={styles.followerTxt}>UpVotes</Text>
<Text style={styles.UpVote}>{userdata.upvotes.length}</Text>
</View>
<View style={styles.verticalLine}></View>
<View style={styles.Postrow1}>
<Text style={styles.followerTxt}>DownVotes</Text>
<Text style={styles.UpVote}>{userdata.donwvotes.length}</Text>
</View>
<View style={styles.verticalLine}></View>
<View style={styles.Postrow1}>
<Text style={styles.followerTxt}>Posts</Text>
<Text style={styles.UpVote}>{userdata.posts.length}</Text>
</View>
</View>
{/* <Text style={styles.decs}>Hello this is des</Text> */}
</View>
{
userdata.posts.length > 0 ? <View style={styles.section1}>
<Text style={styles.postTxt}>Your Posts</Text>
<View style={styles.posts}>
{
userdata.posts.map((item) => {
return (
<Image key={item.id} style={styles.Postimage} source={{ uri: item.posts }} />
)
})
}
</View>
</View>
:
<View style={styles.noPost}>
<Text style={styles.noposttxt}>User not posted anything yet</Text>
</View>
}
</ScrollView>
:
<ActivityIndicator color='white' size='large' />
}
</View>
)
}
export default Profile
my backend code:
router.post('/userdata', (req, res) => {
const { authorization } = req.headers;
if (!authorization) {
return res.status(401).json({ error: 'You must be logged in, token not given' });
}
const token = authorization.replace("Bearer", "");
console.log(token);
jwt.verify(token, process.env.JWT_SECERT, (err, payload) => {
if (err) {
return res.status(401).json({ error: 'You must be logged in, token invalid' })
}
const { _id } = payload;
User.findById(_id).then(
userdata => {
res.status(200).send({ message: 'User Found', user: userdata })
})
})
})
From here i get the user:
const handleLogin = () => {
if (email == '' || password == '') {
alert('Please enter email and password')
}
else {
setLoading(true)
fetch('http://10.0.2.2:3000/login', { // for emultor 'http://10.0.2.2:3000/signup
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
email,
password
})
})
.then(res => res.json())
.then(async data => {
if (data.error) {
setLoading(false)
alert(data.error)
}
else if (data.message == 'Successfully Signed In') {
setLoading(false)
await AsyncStorage.setItem('user', JSON.stringify(data))
navigation.navigate('home', { data })
}
})
.catch(err => {
setLoading(false)
alert(err)
})
}
}
Login code:
router.post('/login', (req, res) => {
const { email, password } = req.body;
if (!email || !password) {
return res.status(422).json({ error: 'Please fill all the fields' })
}
else {
User.findOne({ email: email })
.then(savedUser => {
if (!savedUser) {
return res.status(422).json({ error: 'invaile cnreditnions' })
}
else {
bcrypt.compare(password, savedUser.password)
.then(
doMatch => {
if (doMatch) {
const token = jwt.sign({ _id: savedUser._id }, process.env.JWT_SECERT);
const { _id, username, email } = savedUser;
res.json({ message: 'Successfully Signed In', token, user: { _id, username, email } });
}
else {
return res.status(422).json({ error: 'invaile cnreditnions' })
}
}
)
}
})
.catch(err => {
console.log(err)
})
}
})
Well the error simply indicates that the value that you are trying to parse is not an object rather it is a null value. Try to do optional chaining while re-renders and also check your api response of token. The value coming as response is clearly not an object. Try to debug using console.log(value) and add some error boundaries like loading and error states and accordingly manage the UI. You will be good to go.

undefined is not an object (evaluating '_ref.navigation') React-native navigation error

How to solve this error in react navigation
I am can't able to navigate another screen from passReg() function,
check bellow my full code on my answer
This is my error
THIS IS MY CODE PLZ SOLVE THIS ERROR
import 'react-native-gesture-handler';
import React,{ useState } from 'react';
import { StyleSheet, Text, SafeAreaView, ScrollView , View,Image,FlatList,RefreshControl,AsyncStorage,TextInput} from 'react-native';
import { TouchableRipple,Button} from 'react-native-paper';
import { useNavigation,NavigationContainer} from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
import firebase from 'firebase';
import auth from '#react-native-firebase/auth';
import Reg from './Reg';
const Stack = createStackNavigator();
function passReg({ navigation })
{
navigation.navigate('reg');
}
const PhoneSignIn=()=> {
// If null, no SMS has been sent
const [number, setNumber] = useState(null);
const [confirm, setConfirm] = useState(null);
const [code, setCode] = useState('');
const [flag, setFlag] = useState();
// Handle the button press
async function signInWithPhoneNumber(phoneNumber) {
const addNum = '+91'+phoneNumber;
try{
const confirmation = await auth().signInWithPhoneNumber(addNum);
setConfirm(confirmation);
} catch (error) {
alert(error);
}
}
async function confirmCode() {
try {
await confirm.confirm(code);
if (confirm.confirm(code)) {
AsyncStorage.setItem('mo_num',number);
alert("Congraulation....")
datasend();
}
} catch (error) {
alert(error);
}
}
async function datasend()
{
fetch('https://punjabfoodhub.in/app/reg.php', {
method: 'POST',
mode: 'no-cors',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
'phone_num': number,
})
}).then((response) => response.json())
.then((json) => {
setFlag(json.flag);
if (flag == 'reg') { passReg()}
}).catch((err) => { console.log(err); });
}
if (!confirm) {
return (
<>
<Image
source={require('../assets/cover.png')}
style={styles.image}
/>
<View style={{padding:18}}>
<TextInput
style={styles.input}
placeholder="+91 **********"
onChangeText={num => setNumber(num)}
keyboardType="numeric"
autoCompleteType="tel"
dataDetectorTypes="phoneNumber"
/>
<Button icon="phone" mode="contained" style={styles.btn} onPress={() => passReg()}>
SEND OTP
</Button>
</View>
</>
);
}
return (
<>
<Image
source={require('../assets/cover.png')}
style={styles.image}
/>
<View style={{padding:18}}>
<TextInput
style={styles.input}
maxLength = {6}
onChangeText={text => setCode(text)}
keyboardType="numeric"
placeholder="OTP"
/>
<Button icon="camera" mode="contained" style={styles.btn} onPress={()=> confirmCode()}>
Next
</Button>
<Button mode="text" color="gold" onPress={() => console.log('Pressed')}>
Resend OTP ?
</Button>
</View>
</>
);
}
export default class Login extends React.Component{
constructor(props) {
super(props);
this.state = {
number:null,
otpsend:false,
confirm:null,
otp:null,
};
}
render(){
return(
<ScrollView style={{backgroundColor:'#fff'}}>
<PhoneSignIn/>
<Stack.Navigator headerMode="none">
<Stack.Screen name="main" component={PhoneSignIn} />
<Stack.Screen name="reg" component={Reg} />
</Stack.Navigator>
</ScrollView>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#FBFCFC', //#FFFAFA
paddingHorizontal:12,
//marginTop: Constants.statusBarHeight,
},
image:{
width:'100%',
height:250
},
input:{
borderRadius:20,
borderWidth: 2,
borderColor:'gold',
paddingHorizontal:20,
fontSize:18
, },
btn:{
borderRadius:20,
backgroundColor:'gold',
paddingVertical:5,
marginTop:8
}
});
I believe this has to do with the deconstruction of the navigation prop.
In the line function passReg({ navigation }), there is probably data that's supposed to be there but is not coming through. I'll check back in when I'm able to find the solution for my exact same problem....

Problems with login/Signup on React Native with PHP and MySQL

Login/Signup parameters did not work with local server (MySQL). I have a PHP done to link for my server side authentication.
I tried different parameters for the "username" as well as "password" but it just wont register into my database..
Would really appreciate any help on making it work! Thanks a lot!
import React, { Component } from "react";
import {
ActivityIndicator,
Keyboard,
KeyboardAvoidingView,
ScrollView,
StyleSheet
} from "react-native";
import { Block, Button, Input, Text } from "../components";
import { theme } from "../constants";
// const VALID_USER = "";
// const VALID_PASSWORD = "";
// const login_url = "http://192.168.200.199:80/buildingreg/login.php";
const KEY_STATUS = "status";
const KEY_MESSAGE = "message";
const KEY_FULL_NAME = "full_name";
const KEY_USERNAME = "";
const KEY_PASSWORD = "";
const KEY_EMPTY = "";
export default class Login extends Component {
state = {
username: KEY_USERNAME,
password: KEY_PASSWORD,
errors: [],
loading: false
};
handleLogin() {
const { navigation } = this.props;
const { username, password } = this.state;
const errors = [];
Keyboard.dismiss();
this.setState({ loading: true });
// check with backend API or with some static data
let reg = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if (username === KEY_EMPTY) {
alert("Please enter Email address");
} else if (reg.test(username) === false) {
alert("Username is not correct");
} else if (password === KEY_EMPTY) {
alert("Please enter password");
} else {
fetch(
"http://10.55.1.143/buildingreg/login.php",
{
method: "post",
header: {
Accept: "application/json",
"Content-type": "application/json"
},
body: JSON.stringify({
// we will pass our input data to server
username: username,
password: password
})
},
alert(username, password)
)
.then(response => response.json())
.then(responseJson => {
if (responseJson == "ok" || !errors.length) {
// redirect to profile page
alert("Successfully Login");
navigation.navigate("login");
} else {
alert("Wrong Login Details");
}
})
.catch(error => {
console.error(error);
});
//this.setState({ errors, loading: false });
}
Keyboard.dismiss();
}
render() {
const { navigation } = this.props;
const { loading, errors } = this.state;
const hasErrors = key => (errors.includes(key) ? styles.hasErrors : null);
return (
<KeyboardAvoidingView style={styles.login} behavior="height">
<Block padding={[0, theme.sizes.base]}>
<Text h1 bold>
Login
</Text>
<ScrollView
showsVerticalScrollIndicator={false}
style={{ paddingVertical: theme.sizes.base * 2 }}
>
<Block bottom>
<Input
label="Username"
error={hasErrors("username")}
style={[styles.input, hasErrors("username")]}
defaultValue={this.state.username}
onChangeText={username => this.setState({ username })}
/>
<Input
secure
label="Password"
error={hasErrors("password")}
style={[styles.input, hasErrors("password")]}
defaultValue={this.state.password}
onChangeText={password => this.setState({ password })}
/>
<Button gradient onPress={() => this.handleLogin()}>
{loading ? (
<ActivityIndicator size="small" color="white" />
) : (
<Text bold white center>
Login
</Text>
)}
</Button>
<Button onPress={() => navigation.navigate("Forgot")}>
<Text
gray
caption
center
style={{ textDecorationLine: "underline" }}
>
Forgot your password?
</Text>
</Button>
</Block>
</ScrollView>
</Block>
</KeyboardAvoidingView>
);
}
}
const styles = StyleSheet.create({
login: {
flex: 1,
justifyContent: "center"
},
input: {
borderRadius: 0,
borderWidth: 0,
borderBottomColor: theme.colors.gray2,
borderBottomWidth: StyleSheet.hairlineWidth
},
hasErrors: {
borderBottomColor: theme.colors.accent
}
});

JSON Parse error: Unexpected identifier "Try"

So I am following this guide and my web host works, but a client still get an error:
JSON Parse error: Unexpected identifier "Try"
This is how my register.js code looks like:
import React, { Component } from "react";
import {
StyleSheet,
Text,
View,
StatusBar,
TouchableOpacity,
Alert,
TextInput
} from "react-native";
import { navigation } from "react-navigation";
import Form from "../forms/Form";
export default class Register extends Component<{}> {
constructor(props) {
super(props);
this.state = {
UserName: "",
UserEmail: "",
UserPassword: ""
};
}
UserRegistrationFunction = () => {
const { UserName } = this.state;
const { UserEmail } = this.state;
const { UserPassword } = this.state;
fetch("https://lifestormweb.000webhostapp.com/user_registration.php", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
name: UserName,
email: UserEmail,
password: UserPassword
})
})
.then(response => response.json())
.then(responseJson => {
Alert.alert(responseJson);
})
.catch(error => {
console.error(error);
});
};
render() {
return (
<View style={styles.container}>
<TextInput
style={styles.inputBox}
underlineColorAndroid="#ffffff"
placeholder="Ihre Name"
placeholderTextColor="#ffffff"
selectionColor="#fff"
onChangeText={UserName => this.setState({ UserName })}
onSubmitEditing={() => this.password.focus()}
/>
<TextInput
style={styles.inputBox}
underlineColorAndroid="#ffffff"
placeholder="Ihre E-mail"
placeholderTextColor="#ffffff"
selectionColor="#fff"
keyboardType="email-address"
onChangeText={UserEmail => this.setState({ UserEmail })}
onSubmitEditing={() => this.password.focus()}
/>
<TextInput
style={styles.inputBox}
underlineColorAndroid="#ffffff"
placeholder="Passwort"
secureTextEntry={true}
placeholderTextColor="#ffffff"
onChangeText={UserPassword => this.setState({ UserPassword })}
ref={input => (this.password = input)}
/>
<TouchableOpacity
onPress={this.UserRegistrationFunction}
style={styles.button}
>
<Text style={styles.buttonText}>Sich anmelden</Text>
</TouchableOpacity>
<View style={styles.signupTextCont}>
<Text style={styles.signupText}>Haben Sie schon einen Account?</Text>
<TouchableOpacity
onPress={() => this.props.navigation.navigate("Login")}
>
<Text style={styles.signupButton}> Sich einloggen</Text>
</TouchableOpacity>
</View>
</View>
);
}
}
module.exports = Register;
The response you are fetching is a string value not JSON.You need convert the response maybe like:
{"result": "Something went wrong.Try again", code: "500"}
Code will verify if the server side response don't have issues.
I tried to make a post request on your mentioned url https://lifestormweb.000webhostapp.com/user_registration.php
and I get this response
which is not a json, so you need to do the handling for such responses in your code, hope it helps!!

Stack navigator giving me undefined error

I'm using https://facebook.github.io/react-native/docs/navigation.html by the way.
I'm trying to use the StackNavigator to go from Login.js to AboutDendro.js. What's wrong in my <Button/> component that's throwing that error in my iOS simulator?
Here's Login.js:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { ScrollView, Text, TextInput, View, Button, StyleSheet } from 'react-native';
import { login } from '../redux/actions/auth';
import {AuthenticationDetails, CognitoUser, CognitoUserAttribute, CognitoUserPool} from '../lib/aws-cognito-identity';
import StackNavigator from 'react-navigation';
import AboutDendro from './AboutDendro';
const awsCognitoSettings = {
UserPoolId: 'something',
ClientId: 'something'
};
class Login extends Component {
constructor (props) {
super(props);
this.state = {
page: 'Login',
username: '',
password: ''
};
}
get alt () { return (this.state.page === 'Login') ? 'SignUp' : 'Login'; }
handleClick (e) {
e.preventDefault();
const userPool = new CognitoUserPool(awsCognitoSettings);
// Sign up
if (this.state.page === 'SignUp') {
const attributeList = [
new CognitoUserAttribute({ Name: 'email', Value: this.state.username })
];
userPool.signUp(
this.state.username,
this.state.password,
attributeList,
null,
(err, result) => {
if (err) {
alert(err);
this.setState({ username: '', password: '' });
return;
}
console.log(`result = ${JSON.stringify(result)}`);
this.props.onLogin(this.state.username, this.state.password);
}
);
} else {
const authDetails = new AuthenticationDetails({
Username: this.state.username,
Password: this.state.password
});
const cognitoUser = new CognitoUser({
Username: this.state.username,
Pool: userPool
});
cognitoUser.authenticateUser(authDetails, {
onSuccess: (result) => {
console.log(`access token = ${result.getAccessToken().getJwtToken()}`);
this.props.onLogin(this.state.username, this.state.password);
},
onFailure: (err) => {
alert(err);
this.setState({ username: '', password: '' });
return;
}
});
}
}
togglePage (e) {
this.setState({ page: this.alt });
e.preventDefault();
}
static navigationOptions = {
title: 'AboutDendro',
};
render() {
const { navigate } = this.props.navigation;
const App = StackNavigator({
Home: { screen: Login },
Profile: { screen: AboutDendro },
});
return (
<ScrollView style={{padding: 20}}>
<Button
title="Go to Jane's profile"
onPress={() =>
navigate('AboutDendro', { name: 'AboutDendro' })
}
/>
<Text style={{fontSize: 27}}>{this.state.page}</Text>
<TextInput
placeholder='Email Address'
autoCapitalize='none'
autoCorrect={false}
autoFocus={true}
keyboardType='email-address'
value={this.state.username}
onChangeText={(text) => this.setState({ username: text })} />
<TextInput
placeholder='Password'
autoCapitalize='none'
autoCorrect={false}
secureTextEntry={true}
value={this.state.password}
onChangeText={(text) => this.setState({ password: text })} />
<View style={{margin: 7}}/>
<Button onPress={(e) => this.handleClick(e)} title={this.state.page}/>
<View style={styles.firstView}>
<Text onPress={(e) => this.togglePage(e)} style={styles.buttons}>
{this.alt}
</Text>
</View>
</ScrollView>
);
}
}
const styles = StyleSheet.create({
buttons: {
fontSize: 12,
color: 'blue',
flex: 1
},
firstView: {
margin: 7,
flexDirection: 'row',
justifyContent: 'center'
}
});
const mapStateToProps = (state, ownProps) => {
return {
isLoggedIn: state.auth.isLoggedIn
};
}
const mapDispatchToProps = (dispatch) => {
return {
onLogin: (username, password) => { dispatch(login(username, password)); }
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Login);
It is because navigation is not in your props. It is a part of your App component you created. But you do nothing with this component.
You should have an App.js file, with your stackNavigator, set your Login component as your default component in your stackNavigator's parameters.
Take a look at this documentation
I try to refactor your code.
in component render maybe you can just write :
render() {
const { navigate } = this.props.navigation;
return (
<ScrollView style={{padding: 20}}>
<Button
title="Go to Jane's profile"
onPress={() =>
navigate('Profile', { name: 'AboutDendro' })
}
/>
<Text style={{fontSize: 27}}>{this.state.page}</Text>
<TextInput
placeholder='Email Address'
autoCapitalize='none'
autoCorrect={false}
autoFocus={true}
keyboardType='email-address'
value={this.state.username}
onChangeText={(text) => this.setState({ username: text })} />
<TextInput
placeholder='Password'
autoCapitalize='none'
autoCorrect={false}
secureTextEntry={true}
value={this.state.password}
onChangeText={(text) => this.setState({ password: text })} />
<View style={{margin: 7}}/>
<Button onPress={(e) => this.handleClick(e)} title={this.state.page}/>
<View style={styles.firstView}>
<Text onPress={(e) => this.togglePage(e)} style={styles.buttons}>
{this.alt}
</Text>
</View>
</ScrollView>
);
}
}
And you separate component StackNavigation below component render() like:
const App = StackNavigator({
Home: { screen: Login },
Profile: { screen: AboutDendro },
});
And then import component App in your index.ios.js like:
import './Login';
just that. Maybe my answer can help you.

Categories