Darren
Darren

Reputation: 2290

Query current user .once('value') in Firestore

I am transitioning a Firebase real-time database to a Firebase Firestore database but am having trouble finding the appropriate reference to query the current user.

onAuthUserListener = (next, fallback) =>
this.auth.onAuthStateChanged(authUser => {
  if (authUser) {
    this.user(authUser.uid)
      .once('value')
      .then(snapshot => {
        const dbUser = snapshot.val();

        // default empty roles
        if (!dbUser.roles) {
          dbUser.roles = [];
        }

        // merge auth and db user
        authUser = {
          uid: authUser.uid,
          email: authUser.email,
          emailVerified: authUser.emailVerified,
          providerData: authUser.providerData,
          ...dbUser,
        };

        next(authUser);
      });
  } else {
    fallback();
  }
});

Most specifically, what would be the replacement for once('value') and snapshot.val();?

I had thought that

.onSnapshot(snapshot => {
  const dbUser = snapshot.val();
  ...

Upvotes: 0

Views: 1898

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598765

The equivalent of once('value' in Firestore is called get(), and the equivalent of val() is data(). Calling get() returns a promise, so:

.get().then(snapshot => {
  const dbUser = snapshot.data();
  ...

If you have a collection of users, where the profile of each user is stored within a document with their UID as its ID, you can load that with:

firebase.firestore().collection('users').doc(authUser.uid)
  .get()
  .then(snapshot => {
    const dbUser = snapshot.val();

Note that this is pretty well covered in the documentation on getting data, so I'd recommend spending some time there and potentially taking the Cloud Firestore codelab.

Upvotes: 3

Related Questions