Home > Back-end >  Firebase Realtime database query from v8 to v9 SDK
Firebase Realtime database query from v8 to v9 SDK

Time:07-22

I have a Firebase Realtime database query written using Firebase version 8 that I'm looking to migrate over to the v9 SDK.

export const getSingleDataWithQuery = async ({ key, email, criteria }) => {
  if (!criteria) return;
  const snapshot = await realTimeDb
    .ref()
    .child(key)
    .orderByChild(query)
    .equalTo(criteria)
    .get();
  const val = snapshot.val();
  if (val) {
    const keys = Object.keys(val);
    return val[keys[0]];
  }
  return null;
};

In this example:

  • key would be the 'users' collection
  • the email field is looking for users by their email
  • and the criteria is the user's actual email ([email protected])

Using Firebase's Read data once and Sorting data documentation I managed to narrow it down to perhaps being this, but I'm not sure if it's correct:

export const getSingleDataWithQuery = async ({ key, query, criteria }) => {
  if (!criteria) return;
  const dbRef = query(ref(realTimeDb, key), orderByChild(email), equalTo(criteria));
  get(dbRef).then(snapshot => {
    if (snapshot.exists()) {
      const val = snapshot.val();
      if (val) {
        const keys = Object.keys(val);
        return val[keys[0]];
      }
    }
  });
  return null;
};

CodePudding user response:

Aside from the fact that you may have swapped query and email in the fragments, the only difference is in the way you handle the asynchronous database call and that likely explains the difference. Since you use then in the second snippet, the function doesn't actually return a promise and so calling it with await it in the caller won't have any effect.

To make those the same again, use await in the second snippet too, instead of then:

export const getSingleDataWithQuery = async ({ key, query, criteria }) => {
  if (!criteria) return;
  const dbRef = query(ref(realTimeDb, key), orderByChild(email), equalTo(criteria));
  const snapshot = await get(dbRef); //            
  • Related