Reputation: 1405
i need to check if username already exists in real time database then prompt user to select another username. it keep saying not found. I think it because of how my data is nested.
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')
}
})
Upvotes: 3
Views: 3893
Reputation: 16132
You are creating a user, then check if that user exists. Check if the user exists before creating the user.
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);
});
}
});
Upvotes: 3