Check user is online in React native

Viewed 265

I have Social App and i want to check user is ONLINE or OFFLINE:

I know about Appstate in react native and I have one page web JS HTML for manage it( Social App)

so my Problem is how can i see user online in myAPP and i can see this in myWeb?

I am having a workaround like this:

class AppStateExample extends Component {
  state = {
    appState: AppState.currentState
  };

  componentDidMount() {
    AppState.addEventListener("change", this._handleAppStateChange);
  }

  componentWillUnmount() {
    AppState.removeEventListener("change", this._handleAppStateChange);
  }

  _handleAppStateChange = nextAppState => {
    if (
      this.state.appState.match(/inactive|background/) &&
      nextAppState === "active"
    ) {
      console.log("App has come to the foreground!");
    }
    this.setState({ appState: nextAppState });
  };

as soon as I'm online => i will add status into firestore 1 data

db.collection("data").doc("userA").set(
....
status:'online'
).then(() => {
    console.log("change status is sussecd");
});

then in MyWeb

 db.collectionGroup('User').where('status', '==','online').onSnapshot(user => {
          someQuery.....//
        })

Is there any other way?

1 Answers

The problem is not so much writing that the user is online, as they'll be active when that happens. The problem is marking them is offline when they lose their connection.

Firestore doesn't have great built-in support for this, as its protocols are connectionless. But there's a solution by combining it with the Realtime Database, and it's documented here: https://firebase.google.com/docs/firestore/solutions/presence

You can also use Realtime Database directly in your app, and manage presence without Cloud Functions or Firestore.

Related