firebase - 在 React native 中检查用户是否在线

标签 firebase react-native google-cloud-firestore

我有社交应用,我想检查用户是在线还是离线:

我知道 React Native 中的 Appstate,我有一页 web JS HTML 用于管理它(社交应用)

所以我的问题是如何在 myAPP 中看到在线用户,并且在 myWeb 中看到这个?

我有这样的解决方法:

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 });
  };

一旦我在线 => 我会将状态添加到 firestore 1 数据中

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

然后在 MyWeb 中

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

还有其他办法吗?

最佳答案

问题不在于写用户在线,因为在线时他们会处于事件状态。问题是当他们失去连接时将他们标记为离线。

Firestore 对此没有很好的内置支持,因为它的协议(protocol)是无连接的。但是有一个将它与实时数据库结合起来的解决方案,它记录在这里:https://firebase.google.com/docs/firestore/solutions/presence

您还可以直接在您的应用中使用实时数据库,并且 manage presence没有 Cloud Functions 或 Firestore。

关于firebase - 在 React native 中检查用户是否在线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67088669/

相关文章:

android - 如何删除 firestore 中具有不同 id 的多个文档?

swift - 从 Firebase 存储下载元数据

ios - 读取当前用户的数据?

javascript - Angular Firestore 查询中的 get() 和 valueChanges() 有什么区别?

android - 如何在 Android 或 iPhone 上以 React Native 方式处理其他应用程序通知?

reactjs - 使用react-native-web实现组件

firebase - 如何基于uid创建用户个人资料并导航到个人资料页面?

javascript - 无法在 .map 函数 react-native 中循环和渲染 FlatList

firebase - 如何在 flutter 中使用分页显示 listview.builder 中的原生广告?

java - 从 firebase 获取数据并将其返回到主线程