How to fire two functions on single button click - javascript

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

Related

How to check a textInput on emptiness

I need your help. I want to check my textInput for an empty filed, when I am pressing a button. Because now my application can route user to target page with empty fields. So I need to check this fields on emptyness. But I don't know how to do it. I will be very glad, if you help me.
This is my component
import React, { Component } from 'react'
import { View, TextInput } from 'react-native'
import { MyButton, ErrorMessage } from '../uikit'
import { FormStyle, InputStyle } from '../constants/styles'
import { LOG_IN } from '../routes'
export class SignIn extends Component {
state = {
isValidPasword: true,
isEqual: true,
isValidMail: true,
currentPassword: ''
}
isEnoughSymbols = (text) => {
if (text.trim().length < 8) {
this.setState({ isValidPasword: false })
}
else {
this.setState({ currentPassword: text, isValidPasword: true })
}
}
isMatch = (text) => {
if (text != this.state.currentPassword) {
this.setState({ isEqual: false })
}
}
isMail = (text) => {
const pattern = /\b[a-z0-9._]+#[a-z0-9.-]+\.[a-z]{2,4}\b/i
let res = text.search(pattern)
res == -1 ? this.setState({ isValidMail: false }) : this.setState({ isValidMail: true })
}
render() {
const { mainContainer, buttons } = FormStyle
const { container, text } = InputStyle
const { isValidPasword, isEqual, isValidMail, currentPassword } = this.state
return (
<View style={mainContainer}>
<View style={container}>
<TextInput
style={text}
placeholder={'Email'}
onEndEditing={(e) => this.isMail(e.nativeEvent.text)}
>
</TextInput>
{
isValidMail ? null : <ErrorMessage errorText={'Invalid email!'} />
}
</View>
<View style={container}>
<TextInput
style={text}
placeholder={'Password'}
secureTextEntry={true}
onEndEditing={(e) => this.isEnoughSymbols(e.nativeEvent.text)}
>
</TextInput>
{
isValidPasword ? null : <ErrorMessage errorText={'Password must have at least 8 symbols!'} />
}
</View>
<View style={container}>
<TextInput
style={text}
secureTextEntry={true}
placeholder={'Confirm password'}
>
</TextInput>
{
isEqual ? null : <ErrorMessage errorText={'Passwords not matching'} />
}
</View>
<View style={buttons}>
<MyButton
name={'confirm'.toUpperCase()}
onPress={() => (isEqual && isValidMail && isValidPasword) ? this.props.navigation.navigate(LOG_IN) : alert('Your data is wrong!')} />
</View>
</View>
)
}
}
Set the value of the text input using state.
E.g.
state = {
/// rest of state
textValue: ""
}
In the TextInput component add a function to set the state onChange, so the textValue changes when the user types, e.g. (e) => this.setState({ textValue: e.nativeEvent.text })
Then you can check if the input is empty with a function that checks for the state value, like if(this.textValue === "") and then handle the empty vs. not-empty condition.
Better way you can make function like this to check empty spaces, Blank value and text length.
function isEmpty(isFieldEmpty) {
isFieldEmpty = isFieldEmpty.trim()
if (!isFieldEmpty || isFieldEmpty == "" || isFieldEmpty.length <= 0) {
return true;
}
else {
return false;
}
}

Redirect after form submit React Native

I have a simple connection form, I want my user to be redirected to my homepage after connection.
action in my form doesn't seem to work as the URL doesn't change after sending the form.
Here is the content of my Login class in my Login.tsx file
constructor(props) {
super(props);
this.state = {
email: "",
password: ""
}
}
handleSubmit() {
const email = this.state.email;
console.log(email);
const password = this.state.password;
console.log(password);
axios.post("http://snapi.epitech.eu/connection", { email, password }
).then(reponse => {
console.log('connect', reponse);
}).catch(error => {
console.log('error', error);
});
}
render() {
//const { dataSource, fromFetch, fromAxios, loading, axiosData } = this.state
return (
<View style={styles.container}>
<Text>Connection</Text>
<form onSubmit={ this.handleSubmit }
action="localhost:19006/home">
<label>email</label>
<TextInput
//name="email"
style={styles.input}
value={ this.state.email }
onChangeText={ email => this.setState({email}) }
//onChange={val => this.onChange('email', val)}
/>
<label>password</label>
<TextInput
style={styles.input}
secureTextEntry={true}
value={ this.state.password }
onChangeText={ password => this.setState({password}) }
//onChange={val => this.onChange('password', val)}
/>
<Button title="Inscription"
type="submit"
onPress={this.handleSubmit.bind(this)}
/>
</form>
</View>
);
}
};
You need to use react native navigation like below:
import { NavigationActions } from 'react-navigation';
const routeName = "Home" // string e.g 'Home'
const params = { // object (key value pair)
key1: value1,
key2: value2
}
NavigationActions.navigate({ routeName, params }),
or
this.props.navigation.navigate(routeName, params)

Enzyme won't detect components from React Native Elements

I am testing my component using Jest and Enzyme which has Input component from React Native Elements but I am getting error
Method “simulate” is meant to be run on 1 node. 0 found instead
Here is my code:
import 'react-native';
import React from 'react';
import renderer from 'react-test-renderer';
import { shallow } from 'enzyme';
import TransactionDetails from '../../app/BankingFeatures/components/transactionDetails';
const userProfile = {
data: {
user_profile: {
name: 'ashwith',
payment_status_id: '1234556'
}
}
};
const state = {
name: 'ashwith',
amount: null,
transaction_id: null,
transaction_date: '2019/06/18',
transaction_type: null,
name_status: undefined,
amount_status: undefined,
transaction_id_status: undefined,
transaction_date_status: undefined,
transaction_type_status: undefined,
};
describe('Transaction Test', () => {
const wrapper = shallow(<TransactionDetails
userProfile={userProfile}
/>);
const input = wrapper.find('Input').at(0);
input.simulate('changeText', 'eths');
});
transactionDetails.js
import moment from 'moment';
import React, { Component } from 'react';
import DatePicker from 'react-native-datepicker';
import Spinner from 'react-native-loading-spinner-overlay';
import { Icon, Input, Button } from 'react-native-elements';
import {
View,
Text,
ScrollView,
Platform,
KeyboardAvoidingView,
} from 'react-native';
import { Colors } from '../../Metrics';
import { styles } from '../styles/transactionDetails';
import MainContainer from '../../Utilities/mainContainer';
import * as Errmsg from '../../../config/Contents/errMessages';
import * as Placeholdermsg from '../../../config/Contents/placeHolders';
class TransactionDetails extends Component {
// State
constructor(props) {
super(props);
const { userProfile } = this.props;
const userData = userProfile && userProfile.data && userProfile.data.user_profile;
const dateNow = moment(new Date()).format('YYYY/MM/DD');
this.state = {
name: userData ? userData.name : null,
amount: null,
transaction_id: null,
transaction_date: dateNow,
transaction_type: null,
name_status: undefined,
amount_status: undefined,
transaction_id_status: undefined,
transaction_date_status: undefined,
transaction_type_status: undefined,
};
}
getState = () => this.state;
change = (transaction_id, amount) => this.setState({ transaction_id, amount });
// Validating Transaction
async nameValidation() {
const { name } = this.state;
const name_status = name ? undefined : Errmsg.name;
if (name_status === undefined) {
// this.tranIdInput.focus();
} else {
await this.setState({
name_status
});
}
}
// Validating Transaction Date
async transactionDateValidation() {
const { transaction_date } = this.state;
const transaction_date_status = await transaction_date ? undefined : 'Transaction date required';
if (transaction_date_status === undefined) {
this.tranIdInput.focus();
} else {
await this.setState({
transaction_date_status
});
}
}
// Validating Transaction ID
async transIdValidation() {
const { transaction_id } = this.state;
const transaction_id_status = transaction_id ? undefined : 'Transaction id required';
if (transaction_id_status === undefined) {
// this.transTypenput.focus();
} else {
await this.setState({
transaction_id_status
});
}
}
// Validating Transaction Type
async transTypeValidation() {
const { transaction_type } = this.state;
const transaction_type_status = transaction_type ? undefined : 'Transaction type required';
if (transaction_type_status === undefined) {
this.amountInput.focus();
} else {
await this.setState({
transaction_type_status
});
}
}
// Validating Amount
async amountValidation() {
const { amount } = this.state;
const amount_status = !isNaN(amount) ? amount && amount.length >= 5 ? undefined : 'min you can add 10000' : 'Amount required';
if (amount_status === undefined) {
// this.btnPress();
} else {
await this.setState({
amount_status
});
}
}
// Submitting Transaction details
btnPress() {
const { actions } = this.props;
const {
name,
amount,
transaction_id,
transaction_date,
transaction_type,
} = this.state;
actions.addBankTransactionDetails({
name,
amount,
transaction_id,
transaction_date,
transaction_type,
});
}
render() {
const {
name_status,
amount_status,
transaction_id_status,
transaction_date_status,
transaction_type_status,
} = this.state;
const { addBankTransactionDetails } = this.props;
return (
<MainContainer style={styles.container}>
<Spinner
cancelable
visible={addBankTransactionDetails && addBankTransactionDetails.isLoading}
textContent={'Loading...'}
/>
<KeyboardAvoidingView style={styles.container} behavior={Platform.OS === 'ios' && 'height'}>
<ScrollView
bounces={false}
showsVerticalScrollIndicator={false}
>
<View style={styles.formContainer}>
<Text style={styles.title}>Add Transaction Details</Text>
<Input
placeholder={Placeholdermsg.name}
ref={this.nameInput}
leftIcon={
<Icon
name='user'
size={24}
color={Colors.grey}
type='font-awesome'
/>
}
autoFocus
value={this.state.name}
autoCapitalize='characters'
returnKeyType='next'
onSubmitEditing={() => { this.nameValidation(); }}
onChangeText={(name) => this.setState({ name, name_status: undefined })}
inputStyle={styles.textinput}
containerStyle={styles.textFeildContainer}
inputContainerStyle={styles.textFeild}
errorMessage={(name_status) || null}
/>
<DatePicker
style={styles.dateContainer}
date={this.state.transaction_date}
mode="date"
placeholder="Select transaction date"
format="YYYY/MM/DD"
minDate="2019-01-01"
confirmBtnText="Confirm"
cancelBtnText="Cancel"
iconComponent={
<Icon
name="calendar"
type="entypo"
size={24}
color={Colors.grey}
containerStyle={{
position: 'absolute',
left: 10,
top: 8,
marginLeft: 0
}}
/>
}
customStyles={{
dateIcon: {
position: 'absolute',
left: 0,
top: 4,
marginLeft: 0
},
dateInput: {
height: 50,
marginLeft: 50,
borderWidth: 0,
alignItems: 'flex-start',
}
}}
onCloseModal={() => this.transactionDateValidation()}
onDateChange={async (transaction_date) => { this.setState({ transaction_date, transaction_date_status: undefined }, () => { console.log(transaction_date); }); this.transactionDateValidation(); }}
/>
{
(transaction_date_status !== undefined) &&
<View style={styles.errorContainer}>
<Text style={styles.errText}>{transaction_date_status}</Text>
</View>
}
<Input
ref={(input) => { this.tranIdInput = input; }}
placeholder='Enter transaction id'
leftIcon={
<Icon
name='key'
size={24}
color={Colors.grey}
type='entypo'
/>
}
autoCapitalize='characters'
returnKeyType='next'
onSubmitEditing={() => { this.transIdValidation(); }}
onChangeText={(transaction_id) => this.setState({ transaction_id, transaction_id_status: undefined })}
inputStyle={styles.textinput}
containerStyle={styles.textFeildContainer}
inputContainerStyle={styles.textFeild}
errorMessage={(transaction_id_status) || null}
/>
<Input
ref={(input) => { this.transTypenput = input; }}
placeholder='Enter transaction type'
leftIcon={
<Icon
name='bank'
size={20}
color={Colors.grey}
type='font-awesome'
/>
}
autoCapitalize='characters'
returnKeyType='next'
onSubmitEditing={() => { this.transTypeValidation(); }}
onChangeText={(transaction_type) => this.setState({ transaction_type, transaction_type_status: undefined })}
inputStyle={styles.textinput}
containerStyle={styles.textFeildContainer}
inputContainerStyle={styles.textFeild}
errorMessage={(transaction_type_status) || null}
/>
<Input
ref={(input) => { this.amountInput = input; }}
placeholder='Enter Amount'
leftIcon={
<Icon
name='rupee'
size={24}
color={Colors.grey}
type='font-awesome'
/>
}
keyboardType='numeric'
returnKeyType='done'
onSubmitEditing={() => { this.amountValidation(); }}
onChangeText={(amount) => this.setState({ amount, amount_status: undefined })}
inputStyle={styles.textinput}
containerStyle={styles.textFeildContainer}
inputContainerStyle={styles.textFeild}
errorMessage={(amount_status) || null}
/>
</View>
</ScrollView>
</KeyboardAvoidingView>
<View style={styles.bottomContainer}>
<Button
title="Submit"
buttonStyle={styles.Button}
onPress={() => this.btnPress()}
containerStyle={{ alignSelf: 'stretch' }}
/>
</View>
</MainContainer>
);
}
}
export default TransactionDetails;
debug
<MainContainer style={{...}}>
<Spinner cancelable={true} visible={false} textContent="Loading..." animation="none" color="white" size="large" overlayColor="rgba(0, 0, 0, 0.25)" />
<KeyboardAvoidingView style={{...}} behavior="height" enabled={true} keyboardVerticalOffset={0}>
<ScrollViewMock bounces={false} showsVerticalScrollIndicator={false}>
<View style={{...}}>
<Text style={{...}}>
Add Transaction Details
</Text>
<ForwardRef(Themed.Input) placeholder="Enter name" leftIcon={{...}} autoFocus={true} value="ashwith" autoCapitalize="characters" returnKeyType="next" onSubmitEditing={[Function: onSubmitEditing]} onChangeText={[Function: onChangeText]} inputStyle={{...}} containerStyle={{...}} inputContainerStyle={{...}} errorMessage={{...}} />
<DatePicker style={{...}} date="2019/06/24" mode="date" placeholder="Select transaction date" format="YYYY/MM/DD" minDate="2019-01-01" confirmBtnText="Confirm" cancelBtnText="Cancel" iconComponent={{...}} customStyles={{...}} onCloseModal={[Function: onCloseModal]} onDateChange={[Function: _callee]} androidMode="default" height={259} duration={300} iconSource={{...}} showIcon={true} disabled={false} allowFontScaling={true} hideText={false} TouchableComponent={[Function]} modalOnResponderTerminationRequest={[Function: modalOnResponderTerminationRequest]} />
<ForwardRef(Themed.Input) placeholder="Enter transaction id" leftIcon={{...}} autoCapitalize="characters" returnKeyType="next" onSubmitEditing={[Function: onSubmitEditing]} onChangeText={[Function: onChangeText]} inputStyle={{...}} containerStyle={{...}} inputContainerStyle={{...}} errorMessage={{...}} />
<ForwardRef(Themed.Input) placeholder="Enter transaction type" leftIcon={{...}} autoCapitalize="characters" returnKeyType="next" onSubmitEditing={[Function: onSubmitEditing]} onChangeText={[Function: onChangeText]} inputStyle={{...}} containerStyle={{...}} inputContainerStyle={{...}} errorMessage={{...}} />
<ForwardRef(Themed.Input) placeholder="Enter Amount" leftIcon={{...}} keyboardType="numeric" returnKeyType="done" onSubmitEditing={[Function: onSubmitEditing]} onChangeText={[Function: onChangeText]} inputStyle={{...}} containerStyle={{...}} inputContainerStyle={{...}} errorMessage={{...}} />
</View>
</ScrollViewMock>
</KeyboardAvoidingView>
<View style={{...}}>
<ForwardRef(Themed.Button) title="Submit" buttonStyle={{...}} onPress={[Function: onPress]} containerStyle={{...}} />
</View>
</MainContainer>

How to call one of multiple functions - 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));
}

Passing checkbox value to show / hide Password via react native

I'm using Firebase auth I will want to add a Check box, it will display the password in the password text box and hide it when it is clicked again
How to Passing checkbox value to show / hide Password?
This is my Login Page Code:
export default class Login extends Component {
constructor(props) {
super(props)
this.state = {
email: '',
password: '',
response: ''
}
this.signUp = this.signUp.bind(this)
this.login = this.login.bind(this)
}
async signUp() {
try {
await firebase.auth().createUserWithEmailAndPassword(this.state.email, this.state.password)
this.setState({
response: 'Account Created!'
})
setTimeout(() => {
this.props.navigator.push({
id: 'App'
})
}, 500)
} catch (error) {
this.setState({
response: error.toString()
})
}
}
async login() {
try {
await firebase.auth().signInWithEmailAndPassword(this.state.email, this.state.password)
this.setState({
response: 'user login in'
})
setTimeout(() => {
this.props.navigator.push({
id: 'App'
})
})
} catch (error) {
this.setState({
response: error.toString()
})
}
}
render() {
return (
<View style={styles.container}>
<View style={styles.containerInputes}>
<TextInput
placeholderTextColor="gray"
placeholder="Email"
style={styles.inputText}
onChangeText={(email) => this.setState({ email })}
/>
<TextInput
placeholderTextColor="gray"
placeholder="Password"
style={styles.inputText}
password={true}
secureTextEntry={true}
onChangeText={(password) => this.setState({ password })}
/>
</View>
<TouchableHighlight
onPress={this.login}
style={[styles.loginButton, styles.button]}
>
<Text
style={styles.textButton}
>Login</Text>
</TouchableHighlight>
<TouchableHighlight
onPress={this.signUp}
style={[styles.loginButton, styles.button]}
>
<Text
style={styles.textButton}
>Signup</Text>
</TouchableHighlight>
</View>
)
}
}
import React, {useState} from 'react';
import {TextInput} from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome5';
const [hidePass, setHidePass] = useState(true);
<TextInput
placeholder="Password"
secureTextEntry={hidePass ? true : false}>
<Icon
name={hidePass ? 'eye-slash' : 'eye'}
onPress={() => setHidePass(!hidePass)} />
<TextInput/>
One way of doing that is to set a state variable like showPassword and toggle it whenever the checkbox is checked. Like so:
import React, { Component } from 'react';
import {
AppRegistry,
Text,
View,
TextInput,
Switch
} from 'react-native';
export default class DemoProject extends Component {
constructor(props) {
super(props);
this.toggleSwitch = this.toggleSwitch.bind(this);
this.state = {
showPassword: true,
}
}
toggleSwitch() {
this.setState({ showPassword: !this.state.showPassword });
}
render() {
return (
<View>
<TextInput
placeholderTextColor="gray"
placeholder="Password"
secureTextEntry={this.state.showPassword}
onChangeText={(password) => this.setState({ password })}
/>
<Switch
onValueChange={this.toggleSwitch}
value={!this.state.showPassword}
/>
<Text>Show</Text>
</View>
)
}
}
AppRegistry.registerComponent('DemoProject', () => DemoProject);
NOTE: This won't work if you set the password prop!!!
So just use a regular TextInput and utilize the secureTextEntry prop.
here is my way of doing it
const LoginScreen = props => {
const [icon, setIcon] = useState("eye-off")
const [hidePassword, setHidePassword] = useState(true)
_changeIcon = () => {
icon !== "eye-off"
? (setIcon("eye-off"), setHidePassword(false))
: (setIcon("eye"), setHidePassword(true))
}
i used native base for textInput
<Input
secureTextEntry={hidePassword}
placeholder="Password"
placeholderTextColor={palette.gray}
/>
<Icon name={icon} size={20} onPress={() => _changeIcon()} />
this will change the secureTextEntry on click
Please correct me if I am wrong, are you asking how to create a check box? If so, you have two routes, either use a 3rd party library from one of the many check boxes on the web or you can create one yourself.
Steps:
download a icon library as such https://github.com/oblador/react-native-vector-icons so you can use the two material design icons from enter link description here eg. checkbox-blank-outline and checkbox-marked to emulate clicked and not clicked
using those two new icons, simply create a new component with what ever functionality you desire and handle all states and such the way you want.
Basic implementation:
Have a state that controls if it was checked or not
Have a onPress function to handle both states and trigger the respective props
// the on press function
onPress = () => {
if (this.sate.checked) {
this.props.checked();
} else {
this.props.unChecked();
}
}
// the rendered component
<Icon name={this.state.checked ? "checkbox-marked" : "checkbox-blank-outline" onPress={this.onPress}/>
this is how i did in simple way,
my checkbox and password component,
<input style={ inputUname } type={this.state.type} placeholder="Password" value={ this.state.password } onChange={this.handlePassword}/>
<Checkbox defaultChecked={false} onSelection={this.showPassword} value="false" name="Checkbox" label="Show password"/>
my state,
this.state = {
type: 'input'
}
here is my show password event,
showPassword(e){
this.setState( { showpassword: !this.state.showpassword }) // this is to change checkbox state
this.setState( { type: this.state.type === 'password' ? 'text' : 'password' }) // this is to change input box type text/password change
}
enter image description here
const [password, setPassword] = useState("")
const [passwordVisible, setPasswordVisible] = useState(true)
<TextInput
mode='outlined'
style={{ flex: 1, marginHorizontal: 20, marginTop: 30 }}
autoCapitalize="none"
returnKeyType="next"
label=' Password '
keyboardType="default"
underlineColorAndroid={'rgba(0,0,0,0)'}
right={<TextInput.Icon color={colors.white} name={passwordVisible ? "eye" : "eye-off"} onPress={onPressEyeButton} />}
text='white'
maxLength={50}
onChangeText={(text) => { setPassword(text) }}
value={password}
defaultValue={password}
theme={styles.textInputOutlineStyle}
secureTextEntry={passwordVisible}
/>
textInputOutlineStyle: {
colors: {
placeholder: colors.white,
text: colors.white,
primary: colors.white,
underlineColor: 'transparent',
background: '#0f1a2b'
}
},
[1]: https://i.stack.imgur.com/C7ist.png
Step1: Create a useState hook to store the initial values of password and secureTextEntry:
const [data, setData] = useState({
password: '',
isSecureTextEntry: true,
});
Step2: Update the state according to the conditions:
<View>
<TextInput
style={styles.textInput}
placeholder="Enter Password"
secureTextEntry={data.isSecureTextEntry ? true : false}
onChangeText={data => {
setData({
password: data,
//OR
/*
//Array destructuring operator to get the existing state i.e
...data
*/
//and then assign the changes
isSecureTextEntry: !data.isSecureTextEntry,
});
}}></TextInput>
<TouchableOpacity
onPress={() => {
setData({
//...data,
isSecureTextEntry: !data.isSecureTextEntry,
});
}}>
<FontAwesome
name={data.isSecureTextEntry ? 'eye-slash' : 'eye'}
color="gray"
size={25}
paddingHorizontal="12%"
/>
</TouchableOpacity>
</View>
<View>
<Input
style={styles.input}
onChangeText={onChangeData}
multiline={false}
secureTextEntry={!showPassword}
textContentType={"password"}
value={data.password}
placeholder="Password"
/>
<TouchableHighlight
style={{
textAlign: "right",
position: "absolute",
right: 20,
bottom: 22,
zIndex: 99999999,
}}
onPress={() => setShowPassword(!showPassword)}
>
<>
{showPassword && (
<Ionicons name="eye-outline" size={22} color="#898A8D" />
)}
{!showPassword && (
<Ionicons name="eye-off-outline" size={22} color="#898A8D" />
)}
</>
</TouchableHighlight>
</View>;

Categories

Resources