How to call one of multiple functions - JavaScript? - javascript

I have three functions:
Change Email
Change password
Change otherData
And One Button to call them ,
when the user changes his data without change Email Or Password I don't wont to call other function Change Email or Change Password just call the function Change other data, and when changing his email with other data like username, location I just want to call Change Email, change other data Function NOT Change Password
So how to handle this, and how to get a current password and save them in my state cuz when I wrote the wrong password, change Other Data function execute?
I'm using Firebase as a backend
Edit Screen
here is my code [React Native App]
import React, { Component } from 'react';
import firebase from "react-native-firebase";
import Icon from 'react-native-vector-icons/Ionicons';
import styles from "../Style/styles";
import AsyncStorage from '#react-native-community/async-storage';
import {
View,
Text,
KeyboardAvoidingView,
StyleSheet,
ActivityIndicator,
TouchableOpacity,
TextInput,
ScrollView
} from 'react-native';
class profileEdit extends Component {
constructor(props) {
super(props);
this.state = {
currentPassword: "",
newPassword: "",
currentUser: {
username: "",
email: "",
city: "",
mobileNumber: "",
},
data: {},
loading: true
}
}
async componentDidMount() {
try {
const userId = firebase.auth().currentUser.uid;
await this.setState({ userId });
console.log("#uid", this.state.userId);
let recentPostsRef = firebase.database().ref(`users/${userId}`);
await recentPostsRef.once('value').then(snapshot => {
this.setState({ currentUser: snapshot.val(), loading: false })
console.log(this.state.currentUser)
}).catch((error) => console.log("#error", error));
} catch (error) {
console.log("#CError", error);
}
}
reauthenticate = (currentPassword) => {
var user = firebase.auth().currentUser;
var cred = firebase.auth.EmailAuthProvider.credential(
user.email, currentPassword);
return user.reauthenticateWithCredential(cred);
}
_updateProfileData = async () => {
if (this.state.currentPassword === "") {
alert("please write your current password first!")
return;
} else {
await this._updateData();
await this.changeEmail();
await this.changePassword();
}
}
changePassword = () => {
if (this.state.currentPassword === "" || this.state.newPassword === "") {
return
} else {
this.reauthenticate(this.state.currentPassword).then(() => {
var user = firebase.auth().currentUser;
user.updatePassword(this.state.newPassword).then(() => {
console.log("Pssword updated!");
this._updateData();
this.setState({ newPassword: "", currentPassword: "" });
}).catch((error) => console.log(error.message));
}).catch((error) => console.log(error.message));
}
}
changeEmail = () => {
this.reauthenticate(this.state.currentPassword).then(() => {
var user = firebase.auth().currentUser;
user.updateEmail(this.state.currentUser.email).then(() => {
console.log("Email updated!");
this._updateData();
}).catch((error) => { console.log(error) });
}).catch((error) => { console.log(error) });
}
_updateData = () => {
const { userId, currentUser } = this.state;
let recentPostsRef = firebase.database().ref(`users/${userId}`);
recentPostsRef.update({
username: currentUser.username,
email: currentUser.email,
city: currentUser.city,
mobileNumber: currentUser.mobileNumber,
}).then(async () => {
let Data = await AsyncStorage.mergeItem('#MyProfile:data', JSON.stringify(currentUser))
console.log(Data)
alert("Great, your profile updated right now!")
}).then(async () => {
await AsyncStorage.getItem('#MyProfile:data')
.then(json => JSON.parse(json))
.then(currentUser => this.setState({ currentUser }))
.catch(error => console.log('#error' + error));
})
}
// _logout = () => {
// firebase.auth().signOut().then(() => {
// alert("Logout successfuly")
// setTimeout(() => {
// this.props.navigation.navigate("SignIn")
// }, 500)
// }).catch((error) => console.log("#error", error));
// }
render() {
const { currentUser, loading } = this.state;
if (loading) {
return (
<View style={{ justifyContent: "center", alignItems: "center", flex: 1 }}>
<Text>Just a moment.</Text>
<ActivityIndicator size="large" color="#1567d3" />
</View>
)
} else {
console.log("Loading False");
return (
<ScrollView scrollEnabled={true}>
<KeyboardAvoidingView behavior="padding" keyboardVerticalOffset={70}>
<View style={{ flex: 1 }}>
<View style={styles.logoSection}>
{/* <SvgComponent height={100} /> */}
<Icon name="ios-contact" size={90} color='#4d8dd6' style={{ marginTop: 9 }} />
<Text style={{ fontSize: 18, color: "#000", margin: 35, marginTop: 7 }}>
{currentUser.username}
</Text>
</View>
{/* //username */}
<View style={style.child}>
<Icon name="ios-contact" size={30} color='#4285f4' style={{ marginTop: 9 }} />
<TextInput
style={style.textInput}
autoCapitalize="words"
value={currentUser.username}
onChangeText={(username) => { this.setState(Object.assign(currentUser, { username: username })) }}
/>
</View>
{/* //Email */}
<View style={style.child}>
<Icon name="md-at" size={30} color='#4285f4' style={{ marginTop: 9 }} />
<TextInput
style={style.textInput}
keyboardType="email-address"
autoCapitalize="words"
value={currentUser.email}
onChangeText={
(email) => { this.setState(Object.assign(currentUser, { email: email })) }
}
/>
</View>
{/* //Password */}
<View style={style.child}>
<Icon name="md-lock" size={30} color='#4285f4' style={{ marginTop: 9 }} />
<TextInput
style={style.textInput}
autoCapitalize="words"
placeholder="current password"
value={this.state.currentPassword}
onChangeText={(currentPassword) => this.setState({ currentPassword })}
/>
</View>
<View style={style.child}>
<Icon name="md-lock" size={30} color='#4285f4' style={{ marginTop: 9 }} />
<TextInput
style={style.textInput}
autoCapitalize="words"
placeholder="New password"
value={this.state.newPassword}
onChangeText={(newPassword) => { this.setState({ newPassword }) }}
/>
</View>
{/* //Location */}
<View style={style.child}>
<Icon name="ios-navigate" size={30} color='#4285f4' style={{ marginTop: 9 }} />
<TextInput
style={style.textInput}
autoCapitalize="words"
placeholder="New City"
value={currentUser.city}
onChangeText={(city) => { this.setState(Object.assign(currentUser, { city: city })) }}
/>
</View>
<View style={style.child}>
<Icon name="ios-call" size={30} color='#4285f4' style={{ marginTop: 9 }} />
<TextInput
style={style.textInput}
autoCapitalize="words"
keyboardType="number-pad"
placeholder="New Mobile Number"
value={currentUser.mobileNumber}
onChangeText={(mobileNumber) => { this.setState(Object.assign(currentUser, { mobileNumber: mobileNumber })) }}
/>
</View>
{/* Logout
<TouchableOpacity style={style.logout} onPress={this._logout}>
<Icon name="md-power" size={25} color='#0496FF' style={{ marginTop: -2 }} />
<Text style={{ paddingLeft: 10 }}>Logout</Text>
</TouchableOpacity>
*/}
</View>
{/* Save */}
<TouchableOpacity onPress={this._updateProfileData}
style={[styles.button, style.saveBtn]}>
<Text style={styles.TextButton}>Save</Text>
</TouchableOpacity>
</KeyboardAvoidingView>
</ScrollView>
);
}
}
}
export default profileEdit;

I think you have two options, option add more variables to state which you can use to compare the new data with and option two use three boolean values, one for password, email and other.
Option 1
constructor(props) {
super(props);
this.state = {
currentPassword: "",
newPassword: "",
email: '',
currentUser: {
username: "",
email: "",
city: "",
mobileNumber: "",
},
username: '',
city: '',
mobileNumber: '',
data: {},
loading: true
}
}
_updateProfileData = async () => {
const { currentPassword, email, currentUser, newPassword,
mobileNumber, username, city } = this.state;
if (currentPassword === "") {
alert("please write your current password first!")
return;
}
if (email !== currentUser.email) {
// email changed update
await this.changeEmail();
}
if (newPassword !== currentPassword) {
// password changed update
await this.changePassword();
}
if (city !== currentUser.city || mobileNumber !== currentUser.mobileNumber || username !== currentUser.username) {
await this._updateData();
}
}
async componentDidMount() {
try {
const userId = firebase.auth().currentUser.uid;
await this.setState({ userId });
console.log("#uid", this.state.userId);
let recentPostsRef = firebase.database().ref(`users/${userId}`);
await recentPostsRef.once('value').then(snapshot => {
const currentUser = snapshot.val();
this.setState({ currentUser: currentUser, email: currentUser.email, username: currentUser.username, city: currentUser.city, mobileNumber: currentUser.mobileNumber, loading: false })
console.log(this.state.currentUser)
}).catch((error) => console.log("#error", error));
} catch (error) {
console.log("#CError", error);
}
}
Option 2, have three booleans, passwordChanged,emailChanged,otherChanged when the user types in one of the inputs, set the value to true and in your _updateProfileData check if the value is true, then update the value.
constructor(props) {
super(props);
this.state = {
currentPassword: "",
newPassword: "",
currentUser: {
username: "",
email: "",
city: "",
mobileNumber: "",
},
data: {},
// boolean values for email, password and other
passwordChanged: false,
emailChanged: false,
otherChanged: false,
loading: true
}
}
_updateProfileData = async () => {
const { currentPassword, passwordChanged, emailChanged, otherChanged } = this.state;
if (currentPassword === "") {
alert("please write your current password first!")
return;
}
if (emailChanged) {
// email changed update
await this.changeEmail();
}
if (passwordChanged) {
// password changed update
await this.changePassword();
}
if (otherChanged) {
await this._updateData();
}
}

Please do the following:
// You have to change the method _updateProfileData as following
_updateProfileData = async () => {
if (this.state.currentPassword === "") {
alert("please write your current password first!")
return;
} if (this.state.currentUser.email === "") {
alert("Email can't be blank")
return;
} if (this.state.currentUser.username === "") {
alert("Username can't be blank")
return;
} if (this.state.currentUser.city === "") {
alert("City can't be blank")
return;
} if (this.state.currentUser.mobileNumber === "") {
alert("Mobile number can't be blank")
return;
} else {
this._getCurrentUserData((oldUserData) => {
if(oldUserData.email !== this.state.currentUser.email) {
await this.changeEmail();
}
if(this.state.newPassword !== this.state.currentPassword) {
await this.changePassword();
}
if(oldUserData.username !== this.state.currentUser.username || oldUserData.city !== this.state.currentUser.city || oldUserData.mobileNumber !== this.state.currentUser.mobileNumber ) {
await this._updateData();
}
);
}
}
// You have to add this method in your component
_getCurrentUserData = (callBack) => {
AsyncStorage.getItem('#MyProfile:data')
.then(json => JSON.parse(json))
.then(currentUser => callBack(currentUser))
.catch(error => console.log('#error' + error));
}

Related

Firestore doesn't save updated data

export class Register extends Component {
constructor(props) {
super(props);
this.state = {
email: "",
CaloricGoal: 0,
};
this.onSignUp = this.onSignUp.bind(this);
}
onSignUp() {
var {
email,
CaloricGoal,
} = this.state;
firebase
.auth()
.createUserWithEmailAndPassword(email, password)
.then((result) => {
firebase
.firestore()
.collection("users")
.doc(firebase.auth().currentUser.uid)
.set({
email,
CaloricGoal,
});
console.log(result);
})
.catch((error) => {
console.log(error);
});
}
render() {
var CaloricGoal =
selectedGoal === 1
? (TDEE * details + TDEE).toFixed(0)
: selectedGoal == 2
? (TDEE - caloricDeficit).toFixed(0)
: TDEE.toFixed(0);
return (
<SafeAreaView
style={{ flex: 1, backgroundColor: "white", alignItems: "center" }}
>
<TextInput
style={styles.inputEmail}
label="email"
placeholder="Email Address"
autoCapitalize="none"
autoCompleteType="none"
autoCorrect="false"
keyboardType="email-address"
onChangeText={(email) => this.setState({ email })}
/>
So I'm trying to save email and CaloricGoal in my firestore document, but email is the only one that saves, CaloricGoal will remain 0, I believe it's because after I insert the values of the function and get the result, the state doesn't update itself so It just returns 0, how can I fix that?

How to fire two functions on single button click

Hello stackoverflow community I am having problem in using onpress method. Actually i want to fire two functions on a single button click like if i press Register button the validate() function and userRegister function works first validate function validate all the fields and then register function registers user into db. I seen setState is responsible for this kind of behaviour since i m new in react native development so i cant implement this kind of functionality
my code :
import React, { Component } from 'react';
import {ToastAndroid, StyleSheet, View, TextInput, Button, Text, Alert } from 'react-native';
export default class Project extends Component {
constructor(props) {
super(props)
this.state = {
UserName: '',
UserEmail: '',
UserPassword: '',
cpassword: "",
UserCity: ''
};
}
Validate=()=>{
if(this.state.UserName == ""){
ToastAndroid.show('Enter UserName',ToastAndroid.SHORT)
}
else if(this.state.UserEmail == ""){
ToastAndroid.show('Enter Email',ToastAndroid.SHORT)
}
else if(this.state.UserPassword == ""){
ToastAndroid.show('Enter Password',ToastAndroid.SHORT)
}
else if(this.state.cpassword == ""){
ToastAndroid.show('Enter Confirm Password',ToastAndroid.SHORT)
}
else if (this.state.UserPassword != this.state.cpassword){
ToastAndroid.show('Password did not match',ToastAndroid.SHORT)
}
else if(this.state.UserCity == ""){
ToastAndroid.show('Enter City Name',ToastAndroid.SHORT)
}
else {
ToastAndroid.show('User Registration Sucessfull', ToastAndroid.SHORT)
}
console.log(this.state)
}
UserRegistrationFunction = () =>{
const {UserName} = this.state;
const {UserEmail} = this.state;
const {UserPassword} = this.state;
const {UserCity} = this.state;
fetch('http://192.168.0.107/loginrn/user_registration.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: this.state.UserName,
email: this.state.UserEmail,
password: this.state.UserPassword,
//confpassword: this.state.cpassword
city : this.state.UserCity,
})
}).then((response) => response.json())
.then((responseJson) => {
// Showing response message coming from server after inserting records.
Alert.alert(responseJson);
}).catch((error) => {
console.error(error);
});
}
render() {
return (
<View style={styles.MainContainer}>
<Text style= {styles.title}>User Registration Form</Text>
<TextInput
placeholder="Enter User Name"
onChangeText={name => this.setState({UserName : name})}
underlineColorAndroid='transparent'
style={styles.TextInputStyleClass}
/>
<TextInput
placeholder="Enter User Email"
onChangeText={email => this.setState({UserEmail : email})}
underlineColorAndroid='transparent'
style={styles.TextInputStyleClass}
/>
<TextInput
placeholder="Enter User Password"
onChangeText={password => this.setState({UserPassword : password})}
underlineColorAndroid='transparent'
style={styles.TextInputStyleClass}
//secureTextEntry={true}
/>
<TextInput
placeholder="Enter User Confirm Password"
onChangeText={cpassword => this.setState({cpassword})}
underlineColorAndroid='transparent'
style={styles.TextInputStyleClass}
//secureTextEntry={true}
/>
<TextInput
placeholder="Enter User City Name"
onChangeText={city => this.setState({UserCity : city})}
underlineColorAndroid='transparent'
style={styles.TextInputStyleClass}
//secureTextEntry={true}
/>
<Button title="Click Here To Register"
onPress={this.Validate}
color="#2196F3" />
<Button title = "Next" onPress={this.UserRegistrationFunction} color = "#2196F3"/>
</View>
);
}
}
Pass the validate function to onPress = {()=> this.validate()}
And then pass the UserRegistrationFunction in validate function at the end.
import React, { Component } from 'react';
import {ToastAndroid, StyleSheet, View, TextInput, Button, Text, Alert } from 'react-native';
export default class Project extends Component {
constructor(props) {
super(props)
this.state = {
UserName: '',
UserEmail: '',
UserPassword: '',
cpassword: "",
UserCity: ''
};
}
Validate=()=>{
if(this.state.UserName == ""){
ToastAndroid.show('Enter UserName',ToastAndroid.SHORT)
}
else if(this.state.UserEmail == ""){
ToastAndroid.show('Enter Email',ToastAndroid.SHORT)
}
else if(this.state.UserPassword == ""){
ToastAndroid.show('Enter Password',ToastAndroid.SHORT)
}
else if(this.state.cpassword == ""){
ToastAndroid.show('Enter Confirm Password',ToastAndroid.SHORT)
}
else if (this.state.UserPassword != this.state.cpassword){
ToastAndroid.show('Password did not match',ToastAndroid.SHORT)
}
else if(this.state.UserCity == ""){
ToastAndroid.show('Enter City Name',ToastAndroid.SHORT)
}
else {
this.UserRegistrationFunction();
}
console.log(this.state)
}
UserRegistrationFunction = () =>{
const {UserName} = this.state;
const {UserEmail} = this.state;
const {UserPassword} = this.state;
const {UserCity} = this.state;
fetch('http://192.168.0.107/loginrn/user_registration.php', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: this.state.UserName,
email: this.state.UserEmail,
password: this.state.UserPassword,
//confpassword: this.state.cpassword
city : this.state.UserCity,
})
}).then((response) => response.json())
.then((responseJson) => {
// Showing response message coming from server after inserting records.
Alert.alert(responseJson);
}).catch((error) => {
console.error(error);
});
}
render() {
return (
<View style={styles.MainContainer}>
<Text style= {styles.title}>User Registration Form</Text>
<TextInput
placeholder="Enter User Name"
onChangeText={name => this.setState({UserName : name})}
underlineColorAndroid='transparent'
style={styles.TextInputStyleClass}
/>
<TextInput
placeholder="Enter User Email"
onChangeText={email => this.setState({UserEmail : email})}
underlineColorAndroid='transparent'
style={styles.TextInputStyleClass}
/>
<TextInput
placeholder="Enter User Password"
onChangeText={password => this.setState({UserPassword : password})}
underlineColorAndroid='transparent'
style={styles.TextInputStyleClass}
//secureTextEntry={true}
/>
<TextInput
placeholder="Enter User Confirm Password"
onChangeText={cpassword => this.setState({cpassword})}
underlineColorAndroid='transparent'
style={styles.TextInputStyleClass}
//secureTextEntry={true}
/>
<TextInput
placeholder="Enter User City Name"
onChangeText={city => this.setState({UserCity : city})}
underlineColorAndroid='transparent'
style={styles.TextInputStyleClass}
//secureTextEntry={true}
/>
<Button title="Click Here To Register"
onPress={()=>this.Validate()}
color="#2196F3" />
<Button title = "Next" onPress={this.UserRegistrationFunction} color = "#2196F3"/>
</View>
);
}
}
As i mentioned below, You can call two function like this (in class component)
login=()=>{
console.log('login')
}
register =()=>{
console.log('register')
}
<Button title = "Next" onPress={()=>[this.user(),this.register()]}/>
According to your requirement, You should use something like this.
import React, { Component } from 'react';
import {
Alert,
View,
Text,
Image,
TouchableOpacity,
Button,
TextInput,
} from 'react-native';
class HomeScreen extends Component {
state = {
date: '',
month: '',
year: '',
isErrorDate: false,
isErrorDateLenght: false,
isErrorMonth: false,
isErrorMonthLength: false,
isErrorYear: false,
isErrorYearLength: false,
};
onChangeDate = value => {
this.setState({
date: value,
isErrorDate: false,
isErrorDateLenght: false,
});
};
onChangeMonth = value => {
this.setState({
month: value,
isErrorMonth: false,
isErrorMonthLength: false,
});
};
onChangeYear = value => {
this.setState({
year: value,
isErrorYear: false,
isErrorYearLength: false,
});
};
doRegister = () => {
console.log('you have registered');
};
checkDate = () => {
//validation part or function
const { date, month, year } = this.state;
let isErrorDate = date.trim() === '' ? true : false;
let isErrorDateLenght =
date.length > 2 || !/^[0-9]+$/.test(date) || date > 31 ? true : false;
let isErrorMonth = month.trim() === '' ? true : false;
let isErrorMonthLength =
month.length > 2 || !/^[0-9]+$/.test(month) || month > 12 ? true : false;
let isErrorYear = year.trim() === '' ? true : false;
let isErrorYearLength =
year.length > 4 || !/^[0-9]+$/.test(year) ? true : false;
if (
isErrorDate ||
isErrorDateLenght ||
isErrorMonth ||
isErrorMonthLength ||
isErrorYear ||
isErrorYearLength
) {
this.setState({
isErrorDate: isErrorDate,
isErrorDateLenght: isErrorDateLenght,
isErrorMonth: isErrorMonth,
isErrorMonthLength: isErrorMonthLength,
isErrorYear: isErrorYear,
isErrorYearLength: isErrorYearLength,
});
Alert.alert('invalid date /month/ year');
} else {
//submit date and call other functions
this.doRegister();
}
};
render() {
return (
<View style={{ flex: 1 }}>
<View>
<View>
<View style={{ padding: 10 }}>
<TextInput
placeholder="DD"
keyboardType="number-pad"
value={this.state.date}
onChangeText={this.onChangeDate}
/>
</View>
<View style={{ padding: 10 }}>
<TextInput
placeholder="MM"
keyboardType="number-pad"
value={this.state.month}
onChangeText={this.onChangeMonth}
/>
</View>
<View style={{ padding: 10 }}>
<TextInput
placeholder="AA"
keyboardType="number-pad"
value={this.state.year}
onChangeText={this.onChangeYear}
/>
</View>
</View>
</View>
<View>
<Button title ="Next" onPress={this.checkDate}/>
</View>
</View>
);
}
}
export default HomeScreen;
Change this according to your requirement. Feel free for doubts

To Apply the validation and set the password and confirm password same in react native

i'm new in react native. i want to apply the validation if all the fields are filled then it will proceed and if the inputs are not filled it show error and also the pass and confirm password should match . i have applied firebase auth and firebase realtime database.
I have tried many things but none of them working . please help me out in this
export default class LoginForm extends Component {
constructor(props) {
super(props);
this.focusNextField = this.focusNextField.bind(this);
// to store our input refs
this.inputs = {};
this.state = { email: "", password: "", error: "", confirmPassword: "" };
const { password, confirmPassword } = this.state;
}
focusNextField(id) {
this.inputs[id].focus();
}
componentDidMount() {}
static navigationOptions = {};
onEnterText = email => {
if (email.trim() != 0) {
this.setState({ email: email, ErrorStatus: true });
} else {
this.setState({ email: email, ErrorStatus: false });
}
};
onButtonPress = () => {
const { email } = this.state;
if (email == "") {
Alert.alert("Please enter the text to proceed");
} else {
this.setState({ loading: false });
const { email, password } = this.state;
firebase
.auth()
.createUserWithEmailAndPassword(email, password)
.then(response => {
firebase
.auth()
.currentUser.updateProfile({
displayName: email,
displaypassword: password
})
.then(() => {
// Alert.alert(response.user.uid);
// firebase.database().ref('fir-login-67a47/' +
firebase
.auth()
.currentUser.uid()
.set(firebase.auth().currentUser);
firebase
.database()
.ref("sevenup-a1db1//" + firebase.auth().currentUser.uid)
.set({
email,
password
})
.then(data => {
//success callback
// console.log('data ' , data)
});
// .catch((error)=>{
// //error callback
// console.log('error ' , error)
// })
firebase
.database()
.ref("sevenup-a1db1/" + firebase.auth().currentUser.uid)
.on("value", function(snapshot) {
// console.log(snapshot.val())
});
firebase
.database()
.ref("sevenup-a1db1/" + firebase.auth().currentUser.uid)
.update({
email,
password
});
})
.then(() => {
this.props.navigation.navigate("welcome");
})
.catch(error => {
// let errorCode = error.code
// let errorMessage = error.message;
// if (errorCode == 'auth/weak-password') {
// this.onLoginFailure.bind(this)('Weak password!')
// } else {
// this.onLoginFailure.bind(this)(errorMessage)
// }
});
// console.log(onLoginSuccess.uid)
//
console.log(firebase.auth().createUserWithEmailAndPassword.uid);
});
}
};
onLoginSuccess() {
this.setState({
email: "",
password: "",
error: "",
loading: false,
confirmpassword: "",
username: ""
});
}
onLoginFailure(errorMessage) {
this.setState({ error: errorMessage, loading: false });
}
renderButton() {
if (this.state.loading) {
return (
<View style={styles.spinnerStyle}>
<ActivityIndicator size={"small"} />
{/* {this.onButtonPress.bind(this)} */}
{/* loading={this.onButtonPress.bind(this)} */}
</View>
);
} else {
return (
<Button
style={styles.loginButton}
title="Sign in"
// onPress = {this.handleSubmit}
onPress={this.onButtonPress.bind(this)}
/>
);
}
}
render() {
return <View>{this.renderComponent()}</View>;
}
renderComponent() {
if (this.state.loggedIn) {
return (
<Button
title="Sign out"
onPress={() => this.props.navigation.navigate("LoginScreen")}
title="LoginScreen"
/>
);
} else {
return <LoginForm />;
}
}
render() {
return (
<View
style={{
justifyContent: "center",
alignItems: "center",
marginTop: 100
}}
>
<TextInput
style={{
height: 40,
width: 250,
borderRadius: 5,
multiline: "true",
borderColor: "purple",
borderWidth: 2
}}
label="username"
placeholder="username"
// onChange1={this.handleChange}
value={this.state.username}
secureTextEntry={false}
onChangeText={username => this.setState({ username })}
onSubmitEditing={() => {
this.focusNextField("user#mail.com");
}}
returnKeyType={"next"}
ref={input => {
this.inputs["username"] = input;
}}
/>
<TextInput
style={{
height: 40,
width: 250,
borderRadius: 5,
multiline: "true",
borderColor: "purple",
borderWidth: 2,
marginTop: 30
}}
label="Email"
placeholder="user#mail.com"
onSubmitEditing={() => {
this.focusNextField("password");
}}
returnKeyType={"next"}
ref={input => {
this.inputs["user#mail.com"] = input;
}}
value={this.state.email}
secureTextEntry={false}
onChangeText={email => this.onEnterText(email)}
/>
<TextInput
style={{
height: 40,
width: 250,
borderRadius: 5,
multiline: "true",
borderColor: "purple",
borderWidth: 2,
marginTop: 30
}}
label="Password"
placeholder="password"
value={this.state.password}
onSubmitEditing={() => {
this.focusNextField("confirmpassword");
}}
returnKeyType={"next"}
ref={input => {
this.inputs["password"] = input;
}}
secureTextEntry={true}
onChangeText={password => this.setState({ password })}
/>
<TextInput
style={{
height: 40,
width: 250,
borderRadius: 5,
multiline: "true",
borderColor: "purple",
borderWidth: 2,
marginTop: 30
}}
label="confirmpassword"
placeholder="confirmpassword"
value={this.state.confirmpassword}
ref={input => {
this.inputs["confirmpassword"] = input;
}}
secureTextEntry={false}
onChangeText={confirmpassword => this.setState({ confirmpassword })}
/>
<TouchableOpacity
style={{
justifyContent: "flex-end",
alignSelf: "flex-end",
alignItems: "flex-end",
marginRight: 60,
marginTop: 20
}}
onPress={() => this.props.navigation.navigate("LoginScreen")}
title="LoginScreen"
>
<Text>Login</Text>
</TouchableOpacity>
<View style={{ marginTop: 20 }}>{this.renderButton()}</View>
<Text style={styles.errorTextStyle}>{this.state.error}</Text>
</View>
);
}
}
const styles = {
errorTextStyle: {
fontSize: 16,
alignSelf: "center",
color: "red"
},
spinnerStyle: {
flex: 1,
justifyContent: "center",
alignItems: "center"
},
loginButton: {
marginTop: 30
}
};
you can create two states to store data respectively, and then compare both of them.
eg...
this.state={password:'',c_password:''}
and then you can validate with
if(this.state.password !== this.state.c_password){
//your error}
else{
//success
}

React Native List Footer Component does not work

I'm working on React native. I'm using FlatList. I want to show the loading bar as I go down. I wrote the code for that.
I've reviewed the documentation, but it's not working. I guess I'm making a mistake at the await. I don't know how to use it. What is the difference of async? I'm leaving the code sample below.
Thanks in advance for your help.
handleRefresh = () => {
this.setState({
offset: 0,
maxSize: 10,
isSearch: false,
isLoading: true,
isRefreshing: true
}, () => {
this.loadData();
});
};
handleLoadMore = () => {
this.setState({
maxSize: this.state.maxSize + 5,
isSpinner: true
}, () => {
this.loadData();
});
};
keyExtractor = (item, index) => index.toString();
renderFooter = () => {
if(this.state.isSpinner === false) { return null; }
return (
<View style={{ paddingVertical: 20 }}>
<ActivityIndicator animating size="small" />
</View>
);
};
loadData = async () => {
try {
const { offset, maxSize } = this.state;
const username = await AsyncStorage.getItem('username');
const token = await AsyncStorage.getItem('token');
var credentials = Base64.btoa(username + ':' + token);
var URL = `http://demo.espocrm.com/advanced/api/v1/Lead?sortBy=createdAt&asc&offset=${offset}&maxSize=${maxSize}`;
axios.get(URL, {headers : { 'Espo-Authorization' : credentials }})
.then(this.dataSuccess.bind(this))
.catch(this.dataFail.bind(this));
} catch (error) {
Alert.alert(
'Hata',
'Bir hata meydana geldi. Lütfen yöneticiye başvurunuz.',
[
{ text: 'Tamam', onPress: () => null }
]
);
}
};
dataSuccess(response) {
this.setState({ isRefreshing: false, isSpinner: false, isLoading: false, leadList: response.data.list });
}
dataFail(error) {
this.setState({ isLoading: false });
Alert.alert(
'Hata',
'Beklenmedik bir hata oluştu',
[
{ text: 'Tamam', onPress: () => null }
]
);
}
render() {
const { isLoading, isRefreshing, searchText, leadList } = this.state;
return(
<View style={styles.container}>
<SearchBar
placeholder="Bir lead arayın..."
onChangeText={this.searchLead.bind(this)}
onClear={this.handleRefresh}
onCancel={this.loadData}
value={searchText}
/>
{
isLoading ? <ActivityIndicator style={styles.loading} size="large" color="orange" /> :
<FlatList
data={leadList}
ListFooterComponent={this.renderFooter}
renderItem={({item}) =>
<ListItem
leftAvatar={{ source: { uri: 'https://pbs.twimg.com/profile_images/567081964402790401/p7WTZ0Ef_400x400.png' } }}
title={item.name}
subtitle={item.status}
bottomDivider={true}
/>
}
keyExtractor={this.keyExtractor}
refreshing={isRefreshing}
onRefresh={this.handleRefresh}
onEndReached={this.handleLoadMore}
onEndReachedThreshold={0.5}
/>
}
</View>
)
}
}
In your FlatList component, you need to include an attribute called extraData and set that to this.state so the component will update.
<FlatList
data={leadList}
extraData={this.state}
...
/>

Getting an error that's coming out of no where in React Native app

I really can't see how I'm getting undefined is not object (evaluating 'ReactPropTypes.string) error in my iOS simulator. My code in the WebStorm IDE isn't throw me any errors. I've tried deleting my node_modules folder and then running npm install in Terminal because that usually solves most problems, but not in this case.
Here's Secured.js:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { ScrollView, Text, View, Button } from 'react-native';
import { logout } from '../redux/actions/auth';
import DropdownMenu from 'react-native-dropdown-menu';
import Icon from './Icon';
class Secured extends Component {
render() {
var data = [["Choice 1"], ["Choice 2"], ["Choice 3"], ["Choice 4"]];
return(
<ScrollView style={{padding: 20}}>
<Icon/>
<Text style={{fontSize: 27}}>
{`Welcome ${this.props.username}`}
</Text>
<View style={{flex: 1}}>
<DropdownMenu style={{flex: 1}}
bgColor={"purple"} //the background color of the head, default is grey
tintColor={"white"} //the text color of the head, default is white
selectItemColor={"orange"} //the text color of the selected item, default is red
data={data}
maxHeight={410} // the max height of the menu
handler={(selection, row) => alert(data[selection][row])} >
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}} >
</View>
</DropdownMenu>
</View>
<View style={{margin: 20}}/>
<Button onPress={(e) => this.userLogout(e)} title="Logout"/>
</ScrollView>
);
}
}
const mapStateToProps = (state, ownProps) => {
return {
username: state.auth.username
};
}
const mapDispatchToProps = (dispatch) => {
return {
onLogout: () => { dispatch(logout()); }
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Secured);
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';
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();
}
render() {
return (
<ScrollView style={{padding: 20}}>
{/*<Text style={styles.title}>Welcome!</Text>*/}
<TextInput
style={styles.pw}
placeholder=' Email Address'
autoCapitalize='none'
autoCorrect={false}
autoFocus={true}
keyboardType='email-address'
value={this.state.username}
onChangeText={(text) => this.setState({ username: text })} />
<TextInput
style={styles.pw}
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={{margin: 7, flexDirection: 'row', justifyContent: 'center'}}>
<Text onPress={(e) => this.togglePage(e)} style={styles.buttons}>
{this.alt}
</Text>
</View>
</ScrollView>
);
}
}
const styles = StyleSheet.create({
title: {
fontSize: 27,
textAlign: 'center'
},
icon: {
position: 'absolute'
},
pw: {
paddingRight: 90,
justifyContent: 'flex-end',
marginBottom: 20,
backgroundColor: '#9b42f4',
height: 40,
borderWidth: 1,
borderRadius: 5
},
buttons: {
fontFamily: 'AvenirNext-Heavy'
}
});
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);
Check this out, this looks like the issue you're having https://github.com/facebook/react-native/issues/14588#issuecomment-309683553
npm install react#16.0.0-alpha.12 solves the problem.

Categories

Resources