Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to query Firebase Realtime Database using on() in JavaScript?

I’m trying to query a Firebase Realtime Database to retrieve a specific user based on their email using JavaScript. I want to use the equalTo and orderByChild methods together in my query, but I’m encountering issues. Here’s the code snippet I have:

const usersRef = ref(database, 'users');
const userEmail = "testemail123@gmail.com";

const query = query(usersRef, orderByChild('email'), equalTo(userEmail));

emailQuery.on('value', (snapshot) => {
        if (snapshot.exists()) {
          // The user with the email address `userEmail` was found.
          const user = snapshot.val();
          console.log(user)
        } else {
          // The user with the email address `userEmail` was not found.
        }
      });

However, when I run this code, I get an error indicating that emailQuery.on is not defined. It seems that I cannot use on() directly within the query function.

Sign-in error: emailQuery.on is not a function

How can I define "on()"? How can I modify my code to achieve my desired functionality?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I already tried other functions like once or forEach but they seem to provide the same error.

I’ve also tried this code:

      const usersRef = ref(database, 'users');
      console.log(usersRef);

      usersRef.orderByChild('email').equalTo(userEmail)
      .once('value').then((snapshot) => {
        const userObject = snapshot.val();
        console.log(userObject);
      })

but it just provides me this error:

Sign-in error: usersRef.orderByChild is not a function

>Solution :

You’re mixing SDK versions/syntaxes.

This line uses the modular syntax introduced in SDK version 9:

const query = query(usersRef, orderByChild('email'), equalTo(userEmail));

But in this line you then try to use the namespaced API calls that have always existed:

emailQuery.on('value', (snapshot) => {

While both syntaxes continue to be supported, you can’t use mix and match them at will. In a single file you will have to use one or the other.

The equivalent of ref.on(...) in the modular syntax, is the global onValue function as shown in the Firebase documentation on listening for value events.

Based on that, you’d need:

onValue(emailQuery, (snapshot) => {
  ...
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading