反应本地firebase检查用户是否已经存在于实时数据库中

时间:2019-05-28 03:06:47

标签: javascript react-native firebase-realtime-database firebase-authentication

我需要检查用户名是否已经存在于实时数据库中,然后提示用户选择另一个用户名。它一直说找不到。我认为是因为我的数据是如何嵌套的。

enter image description here

signup.js

const { email, username, password } = this.state;

    await firebase
                .auth()
                .createUserWithEmailAndPassword(email, password)
                .then(async user => {
                    console.log('Data created', user);
                    let rootRef = firebase.database().ref()

                rootRef.child("users")
                        .orderByChild("username")
                        .equalTo(username)
                        .once("value")
                        .then(snapshot => {
                            if (snapshot.exists()) {
                                    let userData = snapshot.val()
                                console.log(userData)
                              Alert.alert('username is taken')
                                return userData;
                            }else {
                                console.log('not found')

                            }
                    })

1 个答案:

答案 0 :(得分:1)

您正在创建一个用户,然后检查该用户是否存在。创建用户之前,请检查该用户是否存在。

const { email, username, password } = this.state;

let rootRef = firebase.database().ref();

rootRef
  .child('users')
  .orderByChild('username')
  .equalTo(username)
  .once('value')
  .then(snapshot => {
    if (snapshot.exists()) {
      let userData = snapshot.val();
      console.log(userData);
      Alert.alert('username is taken');
      return userData;
    } else {
      console.log('not found');
      firebase
        .auth()
        .createUserWithEmailAndPassword(email, password)
        .then(async user => {
          console.log('Data created', user);
        });
    }
});