Firebase Realtime Database listener gets fired twice

I think I found a bug, unless I’m doing something wrong. In my code, I’m setting up a listener for one node and getting data from another node, like this:

import React from "react";
import { firebase } from "../lib/firebase";

export default function Test() {
  React.useEffect(() => {
    const userRef = firebase
      .database()
      .ref("data")
      .orderByChild("addedBy")
      .equalTo("some-user-uid");
    userRef.on("value", (snapshot) => {
      console.log("value", snapshot.val());
    });

    const systemRef = firebase
      .database()
      .ref("data")
      .orderByChild("addedBy")
      .equalTo("system");
    systemRef.get();

    return () => userRef.off()
  }, []);
  return <div>1</div>;
}

When I load the page, the console.log gets fired twice, first time with actual user data, but the second time it shows null.

If I add some data to the user ref, the snapshot in the userRef only contains part of the full data.

If I remove the second block, i.e. systemRef, then everything works as intended, i.e. console.log gets fired once with actual user data and subsequent data additions trigger the on listener with proper contents in the snapshot.

So I was wondering, why getting data with get from the system node somehow affects the listener on user node?

Source: Ask Javascript Questions

LEAVE A COMMENT