I am currently making up a sign up form using react and firebase, and I got stuck at validating whether the username given by the user has been used or not by checking the user list from firebase. Here's a simplified version of my code:
import React, { Component } from 'react';
import * as firebase from 'firebase';
const userList = []
class SignUpForm extends Component {
constructor() {
super();
/*initialize my state*/
}
//get the user list from the database
componentWillMount() {
const users = database.ref('users')
users.once('child_added', snapshot => {
userList.push(snapshot.val())
})
}
/*functions that get username from input and store into the state*/
validateForm() {
//in this.state, 'username' is the text input that the user entered
const { username } = this.state
//this is the function that checks if the username is already in use
const findUsername = (username) => {
userList.map(user => {
if (user.username === username) {
console.log("test")
return true
}
})
}
//if username has been taken
if (findUsername(username)) {
console.log("found the same username in the database")
}
/*other validation checks*/
}
render() {
return(
<div>
{/*input elements, etc*/}
<button onClick={this.validateForm}
</div>
)
}
}
The problem is, when I do console.log(findUsername(username))
, it returns undefined
in my console. However, it still logs the string "test", and runs anything written inside that function. It just doesn't return true
inside the if
statement. I have done many checks in my code, and I can make sure that:
- the array
userList
contains every user I have stored in firebase - this.state.username is the actual text input that the user enters
console.log(user.username === username)
when iterating throughuserList
returns truerender()
function works properly
This is my first time asking a question on Stack Overflow, and I apologize if there is any ambiguity or lack of information in my post.