maxwellgover
maxwellgover

Reputation: 7141

Grabbing the Value of Path in Firebase With Promises

I want to grab the value of a path in Firebase. Say I do

firebaseAuth.onAuthStateChanged(user => {
  var displayName = 
    firebase.database()
    .ref('/users/' + user.uid + '/name/')
    .once('value').then(snapshot => snapshot.val());

    store.dispatch('checkUser', {
        user
        displayName
    });
});

In my console I get a promise as the value of my users displayName, inside of that I see the correct value, but how do I get to it? It throws me an error when I try and set displayName to snapshot.val() in the callback.

enter image description here

enter image description here

Why can't I do this? Seems like in the documentation it's possible.

enter image description here

Upvotes: 1

Views: 209

Answers (2)

Brandon
Brandon

Reputation: 7966

Looks like a syntax problem. Arrow functions have a few valid configurations with brackets etc. that can be tough to sort out (it still bites me sometimes after a year of using ES6).

Here's a few valid versions to consider. This isn't an exhaustive list of possible syntax combinations, but I find it covers most of my use cases:

Standard form, multi line block, brackets. This is the version you use when you have more to do than just return a value (e.g., side effects like dispatch):

(snapshot) => { 
    const displayname = snapshot. val()
    // then you'd dispatch here
     return
 } 

One liner, term after the arrow is assumed to be return value. No assignments on the right side in this version, and no dispatch calls:

  snapshot => snapshot.val()

In-between, multiple lines enclosed by parentheses, but still just one value assumed to be return value:

snapshot => ({
      displayName:  snapshot.val()
    }) 
  // returns { displayName: "foo"  } 

Upvotes: 1

cartant
cartant

Reputation: 58430

The error is thrown because the syntax is incorrect; it would need to be enclosed in a block:

.once('value').then(snapshot => { const displayName = snapshot.val(); });

However, that won't solve the problem. You need to move the dispatch call into the callback - where the snapshot has been resolved:

firebaseAuth.onAuthStateChanged(user => {
  firebase.database()
    .ref('/users/' + user.uid + '/name/')
    .once('value').then(snapshot => store.dispatch('checkUser', {
      user
      displayName: snapshot.val()
    }));
});

Upvotes: 1

Related Questions