1

I have the following Javascript function which connects to a firebase database to return a users username:

  setUsername(user) {    
    let userID = user.toString()
    let username = 'Steve'

    let userRef = firebaseRef.database().ref('users/' + userID + "/username")
    userRef.off()

    userRef.on('value', (data) => {
      username = data.val()
      console.log(username)
    })

    return username
  }

My issue is that the userRef function takes a moment to run through and retrieve the data from firebase, so the return function happens before that function is finished doing its thing. I know this as it is currently returning 'Steve', but if I add a setTimeout to the return is returns 'Chao' (the name it should be pulling from firebase).

My question is how can I make sure the function has time to connect to firebase at pull the appropriate data before returning the username?

Thanks

Bex
  • 71
  • 5

0 Answers0