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.

1 Answer 1

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
      }
   })
}
Sign up to request clarification or add additional context in comments.

3 Comments

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?
@MichaelNissen You may find the answer here: stackoverflow.com/questions/6847697/…
Alternatively, if you return the promise from your function, you can chain additional then calls on the result to access the user value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.