Home > database >  Firebase Realtime database showing strange behavior
Firebase Realtime database showing strange behavior

Time:10-13

I am using react-native-firebase in an ejected expo app and trying to build a presence detection system in my chat app which will detect that if the message recipient is online and if not when was he/she was last online. The data will be stored as follows in firebase realtime database:

{
 lastSeen:[{
   [userId]:{
    state: boolean
    time: serverTimeStamp
   }
 }]
}

The problem is that firebase console never shows the data and only if recipient is online then app shows this data (even though its not visible in console) but if user is offline then nothing is returned and no error generated. I have set read and write to true in realtimeDB rules. Here is the code I am using:

import database from "@react-native-firebase/database";

export const updateUserLastSeen = (userId) => {
  const userStatusDatabaseRef = database().ref("/lastSeen/"   userId);
  console.log("updatelast", userId);
  userStatusDatabaseRef
    .set({
      state: true,
      time: database.ServerValue.TIMESTAMP,
    })
    .then(() => console.log("online"))
    .catch((e) => console.log(e));
  // database()
  //   .ref(".info/connected")
  //   .on("value", function (snapshot) {
  //     if (snapshot.val() == false) {
  //       return;
  //     }

  userStatusDatabaseRef
    .onDisconnect()
    .set({
      state: false,
      time: database.ServerValue.TIMESTAMP,
    })
    .then(function () {
      console.log("disconnect configured");
      // userStatusDatabaseRef.set({
      //   state: true,
      //   time: database.ServerValue.TIMESTAMP,
      // });
    });
  // });
};

export const checkUserLastSeen = (userId, setUserLastSeen) => {
  console.log("check last", userId);
  database()
    .ref("/lastSeen/"   userId)
    .on("value", (snapshot) => {
      setUserLastSeen(snapshot.val());
      console.log("User data: ", snapshot.val());
    });
  console.log("after check last");
};

I tried both the code from firebase docs and rnfirebase docs. In above code, none of the "then" or "catch" functions get called in updateUserLastSeen but in checkUserLastSeen "on" is invoked only if bearer of userId is online. Also, I am using realtime db only for this purpose and cloud firestore for other data storing and its working fine. Any help would be appreciated. Thanks.

CodePudding user response:

If neither then nor catch of a write is called, it typically means that the client is not connected to the server.

I recommend checking to make sure your app has a network connection, and that you've configured the (correct) URL for your database.

  • Related