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>