Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
914 views
in Technique[技术] by (71.8m points)

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

I have three functions:

  1. Change Email
  2. Change password
  3. 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

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>
                  

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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();
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...