0

I am having a problem that I am apparently to stupid to solve.. I've been trying to solve this problem for to long, and it doesn't seem to crack.

I am fetching data from firebase using the following function:

export function fetchUserData(userID) {
   database.ref('users/' + userID).once('value').then(function(snapshot) {
      if (!snapshot) {
         console.log('An error occured');
      } else {
         let user = {
            first_name: snapshot.val().first_name,
            last_name: snapshot.val().last_name,
         }
         console.log(user);
         return user
      }
   })
}

That function is returning an object, which I am trying to set in state when the component is mounting:

componentWillMount() {
   this.setState({
      userData: fetchUserData('10212667682706511')
   })
}

If I then try to log the userData to the console when the component is mounted, I get undefined, although logging the user from the fetchUserData function, I get the object:

enter image description here

I am assuming something is getting lost when I call fetchUserData and try to store it in state, but I simply don't know how to fix it, so any help would be appreciated.

AL.
  • 36,815
  • 10
  • 142
  • 281
Michael Nissen
  • 123
  • 1
  • 6

1 Answers1

1

The problem here is that your function fetchUserData returns nothing.

Your code return user returns user from the callback function (the parameter of then()).

One solution for this is to handle data within the callback function:

export function fetchUserData(userID) {
   database.ref('users/' + userID).once('value').then(function(snapshot) {
      if (!snapshot) {
         console.log('An error occured');
      } else {
         // Handle snapshot data here
      }
   })
}
Rax Weber
  • 3,730
  • 19
  • 30
  • Ohh, I totally didn't realise that ! Thank you so, so much! .. I am however wondering if there are other ways of doing this, as I would really like the function: `fetchUserData` to return an object with the data from the snapshot? – Michael Nissen Mar 05 '17 at 19:37
  • 1
    @MichaelNissen You may find the answer here: http://stackoverflow.com/questions/6847697/how-to-return-value-from-an-asynchronous-callback-function – Rax Weber Mar 06 '17 at 04:45
  • Alternatively, if you return the promise from your function, you can chain additional `then` calls on the result to access the `user` value. – fubar Mar 06 '17 at 04:48