更新Redux中Firebase实时数据库中节点的值



每次在数据库中创建新组时,我都想用redux在实时数据库的/categoryId/groupsCount节点中触发一个计数器。我构建这段代码是为了获得该特定类别Id的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查询从/categies/id/groupCounts中获取值?

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

像这样更改您的代码

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

};
};

最新更新