【问题标题】:Update a value from a node in Firebase Realtime-Database in Redux从 Redux 中 Firebase 实时数据库中的节点更新值
【发布时间】:2020-07-13 16:22:00
【问题描述】:

每次在我的数据库中创建一个新组时,我想使用 redux 触发一个计数器进入我的实时数据库中的 /categories/categoryId/groupsCount 节点。我构建了此代码以获取该特定 categoryId 的 groupsCount 值的当前计数,并尝试使用 +1 更新()。它没有用,我找不到任何其他方法来做这个简单的事情。

export const updateCategoryGroupCount = categoryId => {
  return async dispatch => {
    const currentCount = firebase
      .database()
      .ref('/categories/' + categoryId + '/groupsCount')

    await firebase
      .database()
      .ref('/categories/' + categoryId)
      .update({ groupsCount: currentCount + 1 })
      .then(
        dispatch({
          type: UPDATE_CATEGORY_COUNT,
          cid: categoryId,
          total: currentCount + 1;
        })
      );
  };
};

如何使用 firebase 查询从 /categories/id/groupCounts 获取值?

【问题讨论】:

    标签: react-native firebase-realtime-database


    【解决方案1】:

    currentCount 被分配了一个从 firebase 返回的 promise,第二个查询应该在第一个查询完成后调用。

    像这样更改你的代码

    export const updateCategoryGroupCount = categoryId => {
      return async dispatch => {
           firebase
          .database()
          .ref('/categories/' + categoryId + '/groupsCount')
          .once("value")
          .then((snapshot)=> {
             let fetchedObj = snapshot.val(); //the object which is included fields belong to the path of '/categories/' + categoryId + '/groupsCount'
             let currentCount = fetchedObj.currentCount;
    
             await firebase
             .database()
             .ref('/categories/' + categoryId)
             .update({ groupsCount: currentCount + 1 })
             .then(
                dispatch({
                  type: UPDATE_CATEGORY_COUNT,
                  cid: categoryId,
                  total: currentCount + 1;
                })
             );
          })
        
      };
    };
    

    【讨论】:

    • 其实它返回了一个错误:[Unhandled Promise Rejection: TypeError: snapshot is not a function。 (在 'snapshot()' 中,'snapshot' 是 DataSnapshot 的一个实例)]`
    • 我通过改变 fetchedObj 来解决它,让 fetchedObj = snapshot.val();
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-31
    • 1970-01-01
    • 2016-12-08
    • 2022-07-08
    • 2018-07-12
    • 2021-01-13
    相关资源
    最近更新 更多