【问题标题】:How to use firestore real time listeners with redux?如何在 redux 中使用 firestore 实时监听器?
【发布时间】:2020-03-24 14:30:04
【问题描述】:

我有一个 react redux 项目,我想使用 firebase firestore 实时监听器。

现在我有一个获取初始数据的操作:

export const handleInitialData = () => async dispatch => {
  const lists = await firestore.collection('lists').get()

  if (lists) {
    const resolvedLists = lists.docs.map(list => list.data())
    return dispatch(receiveLists(resolvedLists))    
  }
}

你可以看到我使用.collection('lists').get() 并且它有效。

但我想像这样使用.onSnapshot 来使用实时监听器:

export const handleInitialData = () => async dispatch => {
  const lists = await firestore.collection('lists').onSnapshot(snapshop => {
   let changes = snapshop.docChanges()
  })
}

但如果我这样做,我会收到错误: Unhandled Rejection (TypeError): Cannot read property 'map' of undefined

我不知道从这里去哪里......关于让它工作的任何提示?

我看到有这个库https://github.com/prescottprue/react-redux-firebase

但它使用了我讨厌的recompose,而且作者不再推荐。

会有一些帮助。

【问题讨论】:

    标签: firebase redux


    【解决方案1】:

    我得到它的工作不得不这样做:

    export const handleInitialData = () => async dispatch => {
      // const lists = await firestore.collection('lists').get()
      let docs
      const lists = await firestore.collection('lists').onSnapshot(snapshot => {
        docs = snapshot.docChanges().map(c =>c.doc.data())
        if (docs) {
          return dispatch(receiveLists(docs))    
        }
        return
      })
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-20
      • 2020-12-02
      • 1970-01-01
      • 2019-10-28
      • 2021-10-05
      • 1970-01-01
      • 2018-03-27
      • 2021-05-23
      相关资源
      最近更新 更多