How to show Loading on Button press POST request in React Native? - javascript

I am making one Register page in my React Native project. In this page, after filling the form when user presses the Register button one POST request is called. While the POST request response takes some time, I want to show Loading in my screen until I get any response from server.
Here's my code-
import React from 'react';
import { StyleSheet, Text, View, ScrollView, TextInput,
Button,
TouchableHighlight,
Image,
Alert, ActivityIndicator } from 'react-native';
class WelcomeScreen extends React.Component {
constructor() {
super();
this.state = {
first_name:'',
last_name:'',
email : '',
mobile: '',
password:'',
confirmPassword:'',
showLoader:false
}
};
showLoader = () => { this.setState({ showLoader:true }); };
hideLoader = () => { this.setState({ showLoader:false }); };
doSignup(){
this.showLoader();
}
updateValue(text, field) {
if(field == 'first_name') {
this.setState({
first_name: text
})
}
else if(field == 'last_name') {
this.setState({
last_name : text
})
}
else if(field == 'email') {
this.setState({
email : text
})
}
else if(field == 'mobile') {
this.setState({
mobile : text
})
}
else if(field == 'password') {
this.setState({
password : text
})
}
else if(field == 'confirmPassword') {
this.setState({
confirmPassword : text
})
}
}
onClickListener = (viewId) => {
Alert.alert("Alert", "Button pressed "+viewId);
}
submit() {
let collection = {}
collection.first_name = this.state.first_name,
collection.last_name = this.state.last_name,
collection.email = this.state.email,
collection.mobile = this.state.mobile
collection.password = this.state.password,
console.log('#HELLO:', collection);
var url = 'my url';
if(collection.first_name != '' && collection.last_name != '' &&
collection.email != '' && collection.mobile != '' &&
collection.password != '') {
if(this.state.password === this.state.confirmPassword) {
fetch(url, {
method: 'POST',
body: JSON.stringify(collection),
headers: new Headers({
'Content-Type' : 'application/json',
'token': 'token'
})
}).then(res => res.json())
.catch(error=> console.error('Error:', error))
.then(response => console.log('Success:', response));
} else {
Alert.alert('Password and Confirm Password didn\'t match');
}
} else {
Alert.alert('Please fill up the required field');
}
}
render() {
return (
<ScrollView keyboardShouldPersistTaps={'handled'}>
<View style={styles.container}>
<View style={styles.inputContainerEmail}>
<Image style={styles.inputIcon} source={{uri: 'https://png.icons8.com/message/ultraviolet/50/3498db'}}/>
<TextInput style={styles.inputs}
placeholder="Email"
keyboardType="email-address"
underlineColorAndroid='transparent'
onChangeText={(text) => this.updateValue(text, 'email')}/>
</View>
<View style={styles.inputContainer}>
<Image style={styles.inputIcon} source={{uri: 'https://png.icons8.com/key-2/ultraviolet/50/3498db'}}/>
<TextInput style={styles.inputs}
placeholder="Password"
secureTextEntry={true}
underlineColorAndroid='transparent'
onChangeText={(text) => this.updateValue(text, 'password')}/>
</View>
<View style={styles.inputContainer}>
<Image style={styles.inputIcon} source={{uri: 'https://png.icons8.com/key-2/ultraviolet/50/3498db'}}/>
<TextInput style={styles.inputs}
placeholder="Confirm Password"
secureTextEntry={true}
underlineColorAndroid='transparent'
onChangeText={(text) => this.updateValue(text, 'confirmPassword')}/>
</View>
<View style={styles.inputContainer}>
<Image style={styles.inputIcon} source={{uri: 'https://img.icons8.com/ultraviolet/40/000000/administrator-male.png'}}/>
<TextInput style={styles.inputs}
placeholder="First Name"
secureTextEntry={true}
underlineColorAndroid='transparent'
onChangeText={(text) => this.updateValue(text, 'first_name')}/>
</View>
<View style={styles.inputContainer}>
<Image style={styles.inputIcon} source={{uri: 'https://img.icons8.com/ultraviolet/40/000000/administrator-male.png'}}/>
<TextInput style={styles.inputs}
placeholder="Last Name"
secureTextEntry={true}
underlineColorAndroid='transparent'
onChangeText={(text) => this.updateValue(text, 'last_name')}/>
</View>
<View style={styles.inputContainer}>
<Image style={styles.inputIcon} source={{uri: 'https://img.icons8.com/ultraviolet/40/000000/phone.png'}}/>
<TextInput style={styles.inputs}
placeholder="Phone No."
secureTextEntry={true}
underlineColorAndroid='transparent'
textContentType='telephoneNumber'
onChangeText={(text) => this.updateValue(text, 'mobile')}/>
</View>
<TouchableHighlight style={[styles.buttonContainer, styles.loginButton]} onPress=
{()=>{this.submit(); this.doSignup;}}>
<Text style={styles.loginText}>Register</Text>
</TouchableHighlight>
<TouchableHighlight style={styles.buttonContainer} onPress={() => this.onClickListener('restore_password')}>
<Text>Forgot your password?</Text>
</TouchableHighlight>
<TouchableHighlight style={styles.buttonContainerRegister} onPress={() => this.onClickListener('register')}>
<Text>Sign In</Text>
</TouchableHighlight>
</View>
<View style={{ position: 'absolute', top:"50%",right: 0, left: 0 }}>
<ActivityIndicator animating={this.state.showLoader} size="large" color="red" />
</View>
</ScrollView>
);
}
}
I have tried the following solution-
Show loader when button is clicked in react native
But none of them worked in my case. I am not understanding why the Loading is not showing after pressing the Register button as the response is taking some time. So, it would be very nice if someone help to find the problem and give advice to solve it.

You placed the loading view inside the ScrollView, which probably messes up the positioning. Better to wrap the ScrollView in a containing View and place the loading View as a sibling of the ScrollView, show it using conditional rendering.
render() {
return <View style={{flex: 1}}>
<ScrollView style={{flex: 1}}>
{/* contents here */}
</ScrollView>
{
this.state.showLoader && <View style={{ position: 'absolute', top:"50%",right: 0, left: 0 }}>
<ActivityIndicator size="large" color="red" />
</View>
}
</View>;
}

Related

adding data to firestore on user input

Hi im trying to add data to firestore as shown below, but its saying that "undefined is not an object (evaluating "this.state"), i'm taking user email and name etc in by a text input box, why is this failing?
thank you!
import React, {useContext, useState} from 'react'
import { StyleSheet, Text, View, Image, Dimensions, TextInput, Button, TouchableOpacity} from 'react-native'
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'
import { StatusBar } from 'expo-status-bar'
import * as firebase from 'firebase'
import 'firebase/firestore';
import { AuthContext } from '../navigations/AuthProvider'
import {Alert} from 'react-native';
export default class Register extends React.Component {
static navigationOptions = {
headerShown: false
};
constructor(props) {
super(props);
this.state = {
name: "",
email: "",
password: "",
errorMessage: ""
};
}
handleSignUp = () => {
try {
firebase.auth().createUserWithEmailAndPassword(this.state.email, this.state.password)
.then(function(user){
const user2 = firebase.auth().currentUser;
firebase.firestore().collection('users').add({
email: user2.email,
name: user2.displayName
})
});
} catch (err) {
Alert.alert('There is something wrong!', err.message);
}
}
render () {
return (
<KeyboardAwareScrollView>
<View style={styles.container}>
<StatusBar style="auto"/>
<View style={styles.image_view}>
<Image
source={require("../assets/images/dcuhublogo_higherres.png")}
resizeMode="contain"
resizeMode="center"
style={styles.image_style}>
</Image>
</View>
<View style={{
alignSelf: 'center',
marginTop: -50,
marginBottom: 50
}}>
<Text style={{
textAlign: 'center',
fontSize: 17,
color: '#696868'
}}>{'Welcome to DCU Hub! \nSign up to get started.'} </Text>
</View>
<View style={styles.errorMessage}>
{this.state.errorMessage && <Text style={styles.error}>{this.state.errorMessage}</Text>}
</View>
< View style={styles.top_placeholder}>
<TextInput
style={styles.placeholder_text}
placeholder="FULL NAME" autoCapitalize="none" onChangeText={name => this.setState({name})}
value={this.state.name}
></TextInput>
</View>
<View style={styles.placeholder_style}>
<TextInput
style={styles.placeholder_text}
placeholder="DCU EMAIL" autoCapitalize="none" onChangeText={email => this.setState({email})}
value={this.state.email}
></TextInput>
</View>
<View style={styles.placeholder_style}>
<TextInput
style={styles.placeholder_text}
secureTextEntry={true} // SECURE PASSWORD ie hides the texts
placeholder="PASSWORD" secureTextEntry autoCapitalize="none" onChangeText={password => this.setState({password})}
value={this.state.password}
></TextInput>
</View>
{/* THIS ALSO USES FIREBASE AUTHENTICATION
ONCED SIGNED UP, IT SHOULD TAKE THE USER TO THE
CREATE PROFILE SECTION/SCREEN */}
<View>
<Button2 text='SIGN UP' onPress={this.handleSignUp}/>
</View>
<View style={styles.to_signin}>
<Text style={{fontSize: 18}}> Already have an account? </Text>
<TouchableOpacity onPress={() => this.props.navigation.navigate('Login')}>
<Text style={{color: "#d40059", fontSize: 18}}>Sign In</Text>
</TouchableOpacity>
</View>
</View>
</KeyboardAwareScrollView>
);
}
}
I've even tried to use a constructor,
constructor(props) {
super(props);
this.state = {
name: "",
email: "",
password: "",
errorMessage: ""
};
}
and this also fails, what am I doing wrong?
thanks so much!

React native function auto submitting to firebase?

function submit(email, password) {
FirebaseAPI.createUser(email, password)
}
export default function LoginScreen() {
const [email, onChangeText] = React.useState('Enter Email');
const [password, onChangeText2] = React.useState('Enter Password');
const componentDidMount = () => {
this.watchAuthState(this.props.navigation)
}
const watchAuthState =(navigation) => {
firebase.auth().onAuthStateChanged(function(user) {
console.log('onauthStateChanged', user)
if (user) {
this.props.navigation.navigate('Main');
// this.props.navigation.navigate('App');
}
});
}
return (
<KeyboardAvoidingView style={styles.wrapper} behavior="padding">
<View style={styles.scrollViewWrapper}>
<ScrollView style={styles.scrollView}>
<Text style={styles.loginHeader}>Creat an Account </Text>
<TextInput
style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
onChangeText={text => onChangeText(text)}
value={email}
/>
<TextInput
style={{ height: 40, borderColor: 'gray', borderWidth: 1 }}
onChangeText={text => onChangeText2(text)}
value={password}
/>
<TouchableOpacity
style={{marginTop: '5%'}}
onPress= {(submit(email,password))}>
<View>
<Text>Submit</Text>
</View>
</TouchableOpacity>
</ScrollView>
</View>
</KeyboardAvoidingView>
);
}
Firebase is working fine with this function but I have an issue where even if I type say john#gmail.com password sfjkskfs etc it will auto send it to firebase even before I hit the submit button.
Any help would be awesome!
I think you are using the onPress function badly. you should use just like this one :
onPress = {() => this.submit(email,password)}

How to get multiple checkbox values and update to server in react native

I am posting my full code what I am trying. I am trying to get values from multiple checkbox and I have to send in OnButtonClick() function. If the value is true its Y else N I have to send . But I am not able to check the check boxes. Nor unchecked them. Please help I tried something but not succeeded. Please help me with this. It will great help for me .
import React, { Component } from 'react';
import { ImageBackground, ScrollView, TouchableOpacity, View, Platform, Image } from 'react-native';
import { Button, Text, Item, Input, Icon, Form, ListItem, CheckBox, Body, List } from 'native-base';
import Header from '../../ui/header';
import TextFieldTypeClear from '../../ui/textFieldTypeClear';
import SelectField from '../../ui/selectField';
import { PrimaryBtn } from '../../ui/buttons';
import BG from '../../../images/bg.jpg';
import styles from '../../simSwap/SimSwap.style';
import { RegularText, SmallText } from '../../ui/text';
import { ACCOUNT_OWNER,ADDRESS,CYCLE,EMAIL,PHONE,PERIODICITY,CURRENCY,LANGUAGE,EDIT,MAIL,FAX,POST,SMS,WHATSAPP } from '../../../images';
import _ from 'lodash';
const styless = {
icon:{
marginRight:5, marginTop:3
},
label:{
fontSize:14, color:'grey'
}
}
const Label = ({img, textLabel}) =>{
return (
<View style={{flexDirection:'row'}}>
<Image style={styless.icon} source={img}/>
<Text style={styless.label}>{textLabel}</Text>
</View>
);
}
class UpdateBillPreferences extends Component {
constructor(props) {
super(props);
const {navigation,clmmasterData} =this.props;
this.state = {
title: 'Update Bill Preferences',
mobile: navigation.state.params.customer.service.serviceNumber,
icon: 'sim',
email:'',
smsNum:'',
faxNum:'',
languageAndCurrecny:{
preferredLanguage: navigation.state.params.customerInfo[0].billingPreferenceDetails.presentationLanguageCode,
preferredCurrency: navigation.state.params.customerInfo[0].billingPreferenceDetails.preferedCurrencyCode,
},
};
}
componentDidMount() {
}
OnButtonClick = async (preferredLanguage, preferredCurrency,email,smsNum,faxNum) => {
const { OnButtonClick } = this.props;
await OnButtonClick(preferredLanguage, preferredCurrency,email,smsNum,faxNum);
this.setState({
preferredCurrency:'',
preferredLanguage:'',
email :'',
smsNum :'',
faxNum :''
})
}
languageChanged = (key, val) => {
this.handleChange({ field: "preferredLanguage" }, val);
};
handleChange = (props, e) => {
let tempObj = this.state.languageAndCurrecny;
tempObj[props.field] = e;
this.setState({ preferredLanguage: tempObj });
};
render() {
let { title, mobile, icon,languageAndCurrecny } = this.state;
const { navigation,clmmasterData} = this.props;
const {billingAddressDetails,billingPreferenceDetails} = navigation.state.params.customerInfo[0];
const {masterData , language} = clmmasterData;
let submitBtn = { label: 'Submit', OnSubmit: this.onSubmit };
let currencyData=[];
masterData.preferredCurrency.map(({ code: value, name: label }) => {
currencyData.push({ value, label });
});
let languageData=[];
masterData.language.map(({ code: value, name: label }) => {
languageData.push({ value, label });
});
return (
<ImageBackground source={BG} style={styles.imgBG}>
<ScrollView>
<View style={styles.container}>
<View>
<Header title={title} subtitle={mobile} icon={icon} navigation={navigation}/>
</View>
<View style={styles.contentContainer}>
<View style={{ padding: 20 }}>
<Form style={{ width: '100%' }}>
<SelectField
label="Presentation Language"
node="presentationLanguage"
options={languageData}
value={languageAndCurrecny.preferredLanguage}
onChange={this.languageChanged}
that={this}
setIcon={true}
img="LANGUAGE"
/>
<SelectField
label="Preferred Currency"
options={currencyData}
value={languageAndCurrecny.preferredCurrency}
node="preferredCurrency"
onChange={this.languageChanged}
that={this}
setIcon={true}
img="CURRENCY"
/>
<View style={{flexDirection:'column', marginBottom:15}}>
<View>
<Text style={{ color: 'grey', marginBottom: 15, marginTop:10, fontSize:14 }}>Preference</Text>
</View>
<View style={{flexDirection:'row', marginLeft:-10}}>
<View style={{flex:1}}>
<CheckBox color="#00678f" checked={billingPreferenceDetails.isBillByPost === "Y" ? true : false} onPress={() =>this.handleChange()}/>
</View>
<View style={{flex:1}}>
<Text style={{fontSize:14}}>Post</Text>
</View>
<View style={{flex:1}}>
<CheckBox color="#00678f" checked={billingPreferenceDetails.isBillByEmail === "Y" ? true : false} onPress={() =>this.handleChange()}/>
</View>
<View style={{flex:1}}>
<Text style={{fontSize:14}}>Email</Text>
</View>
<View style={{flex:1}}>
<CheckBox color="#00678f" checked={billingPreferenceDetails.isBillBySms === "Y" ? true : false} onPress={() =>this.handleChange()}/>
</View>
<View style={{flex:1}}>
<Text style={{fontSize:14}}>SMS</Text>
</View>
<View style={{flex:1}}>
<CheckBox color="#00678f" checked={billingPreferenceDetails.isBillByFax === "Y" ? true : false} onPress={() =>this.handleChange()}/>
</View>
<View style={{flex:1}}>
<Text style={{fontSize:14}}>FAX</Text>
</View>
</View>
</View>
<View style={{flexDirection:'column', marginBottom:15}}>
<View style={{marginTop:10, marginBottom:10, marginLeft:-3}}>
<Label img={ADDRESS} textLabel="Address"/>
</View>
<View>
<RegularText style={{ fontWeight: 'normal' }} text={`${billingAddressDetails.address1}, ${billingAddressDetails.address2}, ${billingAddressDetails.cityName}, ${billingAddressDetails.state}, ${billingAddressDetails.country}`} textColor="black" />
</View>
</View>
<View style={{marginBottom:15}}>
{billingPreferenceDetails.isBillByEmail === 'Y' &&
<View>
<Label img={EMAIL} textLabel="Email"/>
<Item style={{borderColor: '#00fff', borderBottomWidth:1, marginLeft:0}}>
<Input
value={this.state.email}
onChangeText={(text) => this.setState({email:text})}
/>
</Item>
</View>}
{billingPreferenceDetails.isBillBySms === 'Y' &&
<View>
<Label img={EMAIL} textLabel="SMS"/>
<Item style={{borderColor: '#00fff', borderBottomWidth:1, marginLeft:0}}>
<Input
value={this.state.smsNum}
onChangeText={(text) => this.setState({smsNum:text})}
/>
</Item>
</View>}
{billingPreferenceDetails.isBillByFax === 'Y' &&
<View>
<Label img={EMAIL} textLabel="FAX"/>
<Item style={{borderColor: '#00fff', borderBottomWidth:1, marginLeft:0}}>
<Input
value={this.state.faxNum}
onChangeText={(text) => this.setState({faxNum:text})}
/>
</Item>
</View>}
</View>
<View style={{ marginTop: 50 }}>
<PrimaryBtn label={'submit'} disabled={false} onPress={()=> this.OnButtonClick(this.state.preferredLanguage,this.state.preferredCurrency,
this.state.email,this.state.smsNum,this.state.faxNum)}/>
</View>
</Form>
</View>
</View>
</View>
</ScrollView>
</ImageBackground>
);
}
}
export default UpdateBillPreferences;
Thanks
your code have multiple checkbox,when you clicked checkbox that's value change correct,
i suggest when you clicked check box that checked value store to array using push()
finally you access multiple checkboxs.
If you can shorten your code sample to clarify what needs to change, it might help folks provide a more precise answer. If not, this sample function at least shows how to retrieve the checked status of each checkbox on the page.
The returned object has one property for each checkbox, and the property's value will be "Y" if the corresponding checkbox is checked.
document.getElementById("primaryBtn").addEventListener("click", submit);
function submit(){
const checkboxes = document.querySelectorAll("input[type='checkbox']"); // Finds checkboxes
let formData = {};
for(let checkbox of checkboxes){
formData[checkbox.value] = checkbox.checked ? "Y" : "N"; // Adds one property per checkbox
}
console.log(formData);
return formData;
}
// If you also want a function that notices when a checkbox changes, uncomment this:
/* document.addEventListener("change", handleChange);
function handleChange(event){
if(event.target.type && event.target.type == "checkbox"){
console.log(event.target.value + ": " + event.target.checked);
}
}
*/
<h3>Preference</h3>
<input type="checkbox" value="isBillByPost" />
<label>Post</label>
<br />
<input type="checkbox" value="isBillByEmail" />
<label>Email</label>
<br />
<input type="checkbox" value="isBillBySMS" />
<label>SMS</label>
<br />
<input type="checkbox" value="isBillByFax" />
<label>Fax</label>
<br /><br />
<button id="primaryBtn">Submit</button>

How I can handle multiple checkbox and basis of that show and hide input fields and update to server in react native

In my code there are 2 dropdowns, 4 checkboxes, 4 input fields and one button.
Basically I have to update these fields on button click.
Problem with ckeck box .
I have to make checkbox "checked={true/false}" on condition basis, and I have to take these value and update the server:
1 [] Emal [] sms [] fax (all are unchecked )
Suppose I click on email the email should be checked and one Email input field should appear. And if again I uncheck the checkbox, the input field should be hidden.
If the value is checked Y value should go to server else N value if unchecked when I press the button below .
Basically there are multiple checkboxes and I have to update their value to server . Below Is UX link please see once .
https://xd.adobe.com/view/2b0336f6-6ff6-40ae-6653-f71e080dd0da-5d32/?fullscreen
import React, { Component } from 'react';
import { ImageBackground, ScrollView, TouchableOpacity, View, Platform, Image } from 'react-native';
import { Button, Text, Item, Input, Icon, Form, ListItem, CheckBox, Body, List } from 'native-base';
import Header from '../../ui/header';
import TextFieldTypeClear from '../../ui/textFieldTypeClear';
import SelectField from '../../ui/selectField';
import { PrimaryBtn } from '../../ui/buttons';
import BG from '../../../images/bg.jpg';
import styles from '../../simSwap/SimSwap.style';
import { RegularText, SmallText } from '../../ui/text';
import { ACCOUNT_OWNER,ADDRESS,CYCLE,EMAIL,PHONE,PERIODICITY,CURRENCY,LANGUAGE,EDIT,MAIL,FAX,POST,SMS,WHATSAPP } from '../../../images';
import _ from 'lodash';
const styless = {
icon:{
marginRight:5, marginTop:3
},
label:{
fontSize:14, color:'grey'
}
}
const Label = ({img, textLabel}) =>{
return (
<View style={{flexDirection:'row'}}>
<Image style={styless.icon} source={img}/>
<Text style={styless.label}>{textLabel}</Text>
</View>
);
}
class UpdateBillPreferences extends Component {
constructor(props) {
super(props);
const {navigation,clmmasterData} =this.props;
this.state = {
title: 'Update Bill Preferences',
mobile: navigation.state.params.customer.service.serviceNumber,
icon: 'sim',
email: '',
smsNum: '',
faxNum: '',
isBillByEmail : navigation.state.params.customerInfo[0].billingPreferenceDetails.isBillByEmail,
isBillBySms : navigation.state.params.customerInfo[0].billingPreferenceDetails.isBillByFax,
isBillByFax : navigation.state.params.customerInfo[0].billingPreferenceDetails.isBillBySms,
languageAndCurrecny:{
preferredLanguage: navigation.state.params.customerInfo[0].billingPreferenceDetails.presentationLanguageCode,
},
currencyChangedValue:{
preferredCurrency: navigation.state.params.customerInfo[0].billingPreferenceDetails.preferedCurrencyCode,
}
};
}
componentDidMount() {
}
OnButtonClick = async (preferredLanguage, preferredCurrency,email,smsNum,faxNum) => {
const { OnButtonClick } = this.props;
await OnButtonClick(preferredLanguage, preferredCurrency,email,smsNum,faxNum);
this.setState({
preferredCurrency:'',
preferredLanguage:'',
email :'',
smsNum :'',
faxNum :''
})
}
languageChanged = (key, val) => {
this.handleChange({ field: "preferredLanguage" }, val);
};
handleChange = (props, e) => {
let tempObj = this.state.languageAndCurrecny;
tempObj[props.field] = e;
this.setState({ preferredLanguage: tempObj });
};
currencyChanged = (key, val) => {
this.handleChange2({ field: "preferredCurrency" }, val);
};
handleChange2 = (props, e) => {
let tempObj = this.state.currencyChangedValue;
tempObj[props.field] = e;
this.setState({ preferredCurrency: tempObj });
};
handleChange1 = () => {
let isBillByEmail=this.state.isBillByEmail;
console.log("-----------------------clicked-------");
this.setState(previousState => {
return { isBillByEmail: !previousState.checked };
})
console.log("----------isBillByEmail--------------------",isBillByEmail);
}
render() {
let { title, mobile, icon,languageAndCurrecny,currencyChangedValue,isBillByEmail } = this.state;
const { navigation,clmmasterData} = this.props;
const {billingAddressDetails,billingPreferenceDetails} = navigation.state.params.customerInfo[0];
const {masterData , language} = clmmasterData;
let submitBtn = { label: 'Submit', OnSubmit: this.onSubmit };
let currencyData=[];
masterData.preferredCurrency.map(({ code: value, name: label }) => {
currencyData.push({ value, label });
});
let languageData=[];
masterData.language.map(({ code: value, name: label }) => {
languageData.push({ value, label });
});
return (
<ImageBackground source={BG} style={styles.imgBG}>
<ScrollView>
<View style={styles.container}>
<View>
<Header title={title} subtitle={mobile} icon={icon} navigation={navigation}/>
</View>
<View style={styles.contentContainer}>
<View style={{ padding: 20 }}>
<Form style={{ width: '100%' }}>
<SelectField
label="Presentation Language"
node="presentationLanguage"
options={languageData}
value={languageAndCurrecny.preferredLanguage}
onChange={this.languageChanged}
that={this}
setIcon={true}
img="LANGUAGE"
/>
<SelectField
label="Preferred Currency"
options={currencyData}
value={currencyChangedValue.preferredCurrency}
node="preferredCurrency"
onChange={this.currencyChanged}
that={this}
setIcon={true}
img="CURRENCY"
/>
<View style={{flexDirection:'column', marginBottom:15}}>
<View>
<Text style={{ color: 'grey', marginBottom: 15, marginTop:10, fontSize:14 }}>Preference</Text>
</View>
<View style={{flexDirection:'row', marginLeft:-10}}>
<View style={{flex:1}}>
<CheckBox color="#00678f" checked={billingPreferenceDetails.isBillByPost === "Y" ? true : false}/>
</View>
<View style={{flex:1}}>
<Text style={{fontSize:14}}>Post</Text>
</View>
<View style={{flex:1}}>
<CheckBox color="#00678f" checked={isBillByEmail==='Y'?true : false} onPress={() =>this.handleChange1()}/>
</View>
<View style={{flex:1}}>
<Text style={{fontSize:14}}>Email</Text>
</View>
<View style={{flex:1}}>
<CheckBox color="#00678f" checked={true} onPress={() =>this.handleChange()}/>
</View>
<View style={{flex:1}}>
<Text style={{fontSize:14}}>SMS</Text>
</View>
<View style={{flex:1}}>
<CheckBox color="#00678f" checked={true} onPress={() =>this.handleChange()}/>
</View>
<View style={{flex:1}}>
<Text style={{fontSize:14}}>FAX</Text>
</View>
</View>
</View>
<View style={{flexDirection:'column', marginBottom:15}}>
<View style={{marginTop:10, marginBottom:10, marginLeft:-3}}>
<Label img={ADDRESS} textLabel="Address"/>
</View>
<View>
<RegularText style={{ fontWeight: 'normal' }} text={`${billingAddressDetails.address1}, ${billingAddressDetails.address2}, ${billingAddressDetails.cityName}, ${billingAddressDetails.state}, ${billingAddressDetails.country}`} textColor="black" />
</View>
</View>
<View style={{marginBottom:15}}>
{billingPreferenceDetails.isBillByEmail === 'Y' &&
<View>
<Label img={EMAIL} textLabel="Email"/>
<Item style={{borderColor: '#00fff', borderBottomWidth:1, marginLeft:0}}>
<Input
value={this.state.email}
onChangeText={(text) => this.setState({email:text})}
/>
</Item>
</View>}
{billingPreferenceDetails.isBillBySms === 'Y' &&
<View>
<Label img={EMAIL} textLabel="SMS"/>
<Item style={{borderColor: '#00fff', borderBottomWidth:1, marginLeft:0}}>
<Input
value={this.state.smsNum}
onChangeText={(text) => this.setState({smsNum:text})}
/>
</Item>
</View>}
{billingPreferenceDetails.isBillByFax === 'Y' &&
<View>
<Label img={EMAIL} textLabel="FAX"/>
<Item style={{borderColor: '#00fff', borderBottomWidth:1, marginLeft:0}}>
<Input
value={this.state.faxNum}
onChangeText={(text) => this.setState({faxNum:text})}
/>
</Item>
</View>}
</View>
<View style={{ marginTop: 50 }}>
<PrimaryBtn label={'submit'} disabled={false} onPress={()=> this.OnButtonClick(this.state.preferredLanguage,this.state.preferredCurrency,
this.state.email,this.state.smsNum,this.state.faxNum)}/>
</View>
</Form>
</View>
</View>
</View>
</ScrollView>
</ImageBackground>
);
}
}
export default UpdateBillPreferences;
// Checkbox part where I am facing problem .
Props Value
isBillByEmail: "N"
isBillByFax: "Y"
isBillByPost: "Y"
isBillBySms: "N"
<View style={{flexDirection:'column', marginBottom:15}}>
<View>
<Text style={{ color: 'grey', marginBottom: 15, marginTop:10, fontSize:14 }}>Preference</Text>
</View>
<View style={{flexDirection:'row', marginLeft:-10}}>
<View style={{flex:1}}>
<CheckBox color="#00678f" checked={billingPreferenceDetails.isBillByPost === "Y" ? true : false}/>
</View>
<View style={{flex:1}}>
<Text style={{fontSize:14}}>Post</Text>
</View>
<View style={{flex:1}}>
<CheckBox color="#00678f" checked={isBillByEmail==='Y'?true : false} onPress={() =>this.handleChange1()}/>
</View>
<View style={{flex:1}}>
<Text style={{fontSize:14}}>Email</Text>
</View>
<View style={{flex:1}}>
<CheckBox color="#00678f" checked={true} onPress={() =>this.handleChange()}/>
</View>
<View style={{flex:1}}>
<Text style={{fontSize:14}}>SMS</Text>
</View>
<View style={{flex:1}}>
<CheckBox color="#00678f" checked={true} onPress={() =>this.handleChange()}/>
</View>
<View style={{flex:1}}>
<Text style={{fontSize:14}}>FAX</Text>
</View>
</View>
</View>
<View style={{flexDirection:'column', marginBottom:15}}>
<View style={{marginTop:10, marginBottom:10, marginLeft:-3}}>
<Label img={ADDRESS} textLabel="Address"/>
</View>
<View>
<RegularText style={{ fontWeight: 'normal' }} text={`${billingAddressDetails.address1}, ${billingAddressDetails.address2}, ${billingAddressDetails.cityName}, ${billingAddressDetails.state}, ${billingAddressDetails.country}`} textColor="black" />
</View>
</View>
<View style={{marginBottom:15}}>
{billingPreferenceDetails.isBillByEmail === 'Y' &&
<View>
<Label img={EMAIL} textLabel="Email"/>
<Item style={{borderColor: '#00fff', borderBottomWidth:1, marginLeft:0}}>
<Input
value={this.state.email}
onChangeText={(text) => this.setState({email:text})}
/>
</Item>
</View>}
{billingPreferenceDetails.isBillBySms === 'Y' &&
<View>
<Label img={EMAIL} textLabel="SMS"/>
<Item style={{borderColor: '#00fff', borderBottomWidth:1, marginLeft:0}}>
<Input
value={this.state.smsNum}
onChangeText={(text) => this.setState({smsNum:text})}
/>
</Item>
</View>}
{billingPreferenceDetails.isBillByFax === 'Y' &&
<View>
<Label img={EMAIL} textLabel="FAX"/>
<Item style={{borderColor: '#00fff', borderBottomWidth:1, marginLeft:0}}>
<Input
value={this.state.faxNum}
onChangeText={(text) => this.setState({faxNum:text})}
/>
</Item>
</View>}
</View>
<View style={{ marginTop: 50 }}>
<PrimaryBtn label={'submit'} disabled={false} onPress={()=> this.OnButtonClick(this.state.preferredLanguage,this.state.preferredCurrency,
this.state.email,this.state.smsNum,this.state.faxNum)}/>
</View>
</Form>
</View>
</View>
Please help..Thanks

Undefined TextInput Value

I want to submit value from text input, but when I console.log, the text that inputed before is undefined. I've already follow the instruction from react native get TextInput value, but still undefined.
this is state that I've made before:
this.state = {
comment_value: '',
comments: props.comments
}
submit = (args) => {
this.props.submit(args.comment_value)
}
this is the the function for submitted text:
addComment () {
var comment_value = this.state.comment_value
console.log('success!', comment_value)
})
this.props.submit('410c8d94985511e7b308b870f44877c8', '', 'e18e4e557de511e7b664b870f44877c8')
}
and this is my textinput code:
<TextInput
underlineColorAndroid='transparent'
placeholder='Enter your comment here'
multiline numberOfLines={4}
onChangeText={(text) => this.setState({comment_value: text})}
value={this.state.comment_value}
style={styles.textinput}
/>
</View>
<TouchableOpacity onPress={this.addComment.bind(this)}>
<View style={{flex: 1, flexDirection: 'column', backgroundColor: Colors.background, width: 70}}>
<Icon name='direction' type='entypo' color='#000'size={30} style={styles.icon} />
</View>
</TouchableOpacity>
This should definately be working try cleaning up your code like this
contructor(props) {
super(props);
this.state = {
comment_value: '',
}
}
addComment () {
console.log(this.state.comment_value); // should be defined
this.props.submit(this.state.comment_value);
}
render() {
return (
<View>
<TextInput
underlineColorAndroid='transparent'
placeholder='Enter your comment here'
multiline numberOfLines={4}
value={this.state.comment_value}
onChangeText={(text) => this.setState({comment_value: text})}
style={styles.textinput}
/>
<TouchableOpacity onPress={this.addComment.bind(this)}>
<View style={{flex: 1, flexDirection: 'column', backgroundColor: Colors.background, width: 70}}>
<Icon name='direction' type='entypo' color='#000'size={30} style={styles.icon} />
</View>
</TouchableOpacity>
</View>
);
}
EDIT: Based on your complete code sample it seems like you're incorrectly trying to update state by doing multiple this.state = ... which is incorrect, to update state you have to use this.setState({ ... })

Categories

Resources