3

Everytime I run this script, it shows "not connected" first time and after that "connected". Why does it always trigger "not connected" first? There are some topics with same issue like this one link, but no answers.

var connectedRef = firebase.database().ref(".info/connected");
connectedRef.on("value", function(snap) {
  if (snap.val() === true) {
    alert("connected");
  } else {
    alert("not connected");
  }
});
Red fx
  • 1,071
  • 2
  • 12
  • 26
j22purikas
  • 75
  • 8
  • Please make sure that `snap.val()` contains the true value as string or bool, and then compare accordingly , you can check that by printing the `snap.val()` before `if` – 3stud1ant3 Sep 19 '17 at 07:47
  • Used also JSON.stringify(snap), I see always first time false, and then true. – j22purikas Sep 19 '17 at 07:52

2 Answers2

0

It's a normal, on purpose functionality of Firebase to avoid any race conditions.

Refer the docs: https://firebase.google.com/docs/database/web/offline-capabilities

Note that your app should queue the disconnect operations before a user is marked online, to avoid any race conditions in the event that the client's network connection is lost before both commands can be sent to the server.

Duc Filan
  • 6,769
  • 3
  • 21
  • 26
0

When your page load, the Firebase client is initially not connected to its backend servers. So it marks .info/connected as false.

It then starts building the connection, which may take some time. If/when it established the connection it marks .info/connected as true.

This is the expected behavior. If it is causing problems for your app, it's likely that you're trying to use the indicator for something it may not be directly suitable for. If that is the case, it's probably easier to help if you share your use-case.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thanks, it makes sense now. But basically, I need to show alert , if no firebase connection. Everytime user open page, need to detect if firebase is down or if connection goes down anytime. – j22purikas Sep 19 '17 at 08:04
  • As expected, this is an [XY problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Using `.info/connected` to show a modal alert is a bad user experience. Using it to show a "connected to server" indicator is typically a better user experience. – Frank van Puffelen Sep 19 '17 at 12:13