Related
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)
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
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
}
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));
}
class App extends Component {
constructor(props) {
super(props)
this.state = { text: "", messages: [] }
}
componentDidMount() {
const config = {
apiKey: "<api-key>",
authDomain: "<project-name>.firebaseapp.com",
databaseURL: "https://<project-name>.firebaseio.com",
projectId: "<project-name>",
storageBucket: "<project-name>.appspot.com",
messagingSenderId: "<sender-id>",
};
if (!firebase.apps.length) {
firebase.initializeApp(config);
}
this.getMessages()
var database = firebase.database();
var ref = database.ref('messages');
}
onSubmit = event => {
if (event.charCode === 13 && this.state.text.trim() !== "") {
this.writeMessageToDB(this.state.text)
this.setState({ text: "" })
}
}
writeMessageToDB = () => {
firebase.database().ref('messages/').push({
text: this.state.text,
createdAt: createdAt,
user:{
_id: currentUser,
name:name
}
});
}
getMessages = () => {
var messagesDB = firebase
.database()
.ref("messages/")
.limitToLast(500)
messagesDB.on("value", snapshot => {
let newMessages = []
snapshot.forEach(child => {
var message = child.val()
var yeah = dateFormat(message.createdAt,"dddd, mmmm dS, yyyy, h:MM:ss TT")
newMessages.push({ id: child.key, text: message.text,createdAt: yeah, names: message.name })
})
this.setState({ messages: newMessages })
this.bottomSpan.scrollIntoView({ behavior: "smooth" })
})
}
renderMessages = () => {
return this.state.messages.map(message => (
<ListItem>
<ListItemText className="chatList"
style={{ wordBreak: "break-word", backgroundColor: "#FFA1B5", borderRadius: "10px", width: "10px", padding: "5px" }}
primary={message.name+": "+message.text}
secondary={message.createdAt}
/>
</ListItem>
))
}
render() {
return (
<MuiThemeProvider theme={theme}>
<div style={mainCont}>
<label style={labelStyle} className="labelStyle"> Chat</label>
<div className="App" >
<ScrollToBottom className={ ROOT_CSS }>
<List>{this.renderMessages()}</List>
</ScrollToBottom>
<TextField className="txtFieldStyle"
autoFocus={true}
multiline={true}
rowsMax={3}
placeholder="Type something.."
onChange={event => this.setState({ text: event.target.value })}
value={this.state.text}
onKeyPress={this.onSubmit}
style={{ width: "350px", overflow: "hidden", marginLeft: "15px", fontSize: '63px', paddingBottom: '5px' }}
/>
<span ref={el => (this.bottomSpan = el)} />
</div>
</div>
</MuiThemeProvider>
)
}
}
export default App;
chat feature is working fine unless the user navigates to other pages and go back to the chat feature and attempts to send message through chat.
The following two lines in App.componentDidMount() are a potential race condition.
this.setState({ messages: newMessages })
this.bottomSpan.scrollIntoView({ behavior: "smooth" })
The App state may be mutated earlier to begin a render cycle so that the bottomSpan is set to reference the element before this.bottomSpan.scrollIntoView() is called.
However, this.bottomSpan.scrollIntoView() is never guaranteed to be called after state is updated.
Remember that setState doesn't always immediately mutate the state of the component. [1]
You can scroll the referenced element into view after state is mutated by doing that in a callback passed as the second argument to state.
this.setState(
{ messages: newMessages },
() => this.bottomSpan.scrollIntoView({ behavior: "smooth" })
)