I have been working on a function to check if a username is unique in my Firebase database. Despite researching and implementing code, it doesn't seem to work as expected. Any assistance would be greatly appreciated - what am I missing?
onChangeUsername = (event) => {
var oldError = {...this.state.error};
firebase.database().ref().child("Usernames").orderByValue().once('value', (snapshot) => {
var exists = (snapshot.val() !== null);
console.log(exists);
console.log("hello");
});
if(this.state.validation.username.unique===true)
{oldError.username = "This username is already taken"}
else if((event.nativeEvent.text.length<this.state.validation.username.min) || (event.nativeEvent.text.length>this.state.validation.username.max) )
{oldError.username = "Username should be between " + this.state.validation.username.min + " and " + this.state.validation.username.max + " characters" ;}
else oldError.username = "";
this.setState({ username: event.nativeEvent.text, error:oldError })
}
Here is the structure of my database:
Database:{ Usernames: {uid1: username1, uid2: username2}}
****Question Update **** After Feedback from Frank, I have made some changes to my code. However, it still doesn't produce the desired result. He pointed out some errors that needed correction:
onChangeUsername = (event) => {
var oldError = {...this.state.error};
firebase.database().ref().child("Usernames").orderByKey().equalTo("Username1").once('value', (snapshot) => {
var exists = (snapshot.val() !== null);
console.log(exists);
console.log("hello");
});
if(this.state.validation.username.unique===true)
{oldError.username = "This username is already taken"}
else if((event.nativeEvent.text.length<this.state.validation.username.min) || (event.nativeEvent.text.length>this.state.validation.username.max) )
{oldError.username = "Username should be between " + this.state.validation.username.min + " and " + this.state.validation.username.max + " characters" ;}
else oldError.username = "";
this.setState({ username: event.nativeEvent.text, error:oldError })
}
and my current database setup looks like this:
Database:{ Usernames: {Username1: uid1, Username2: uid2}}