问题描述
我有一个具有不同“程序”(想想帖子或页面)的应用程序,人们可能会喜欢。当前该过程有效:点击like =>运行方法“ likeProcedure” =>运行调度动作“ likeProcedure” =>更新UI。它通常几乎立即发生,但有时会有些滞后,给人一种“非本地”的感觉。我是否有某种方法可以立即返回反馈,同时在Firebase数据库上保留真相的单一来源?
谢谢!
<v-icon
v-if="!userProfile.likedProcedures || !userProfile.likedProcedures[procedure.id]"
color="grey lighten-1"
@click="likeProcedure({ id: procedure.id })"
>
mdi-star-outline
</v-icon>
和
computed: {
...mapState(["userProfile"]),procedures() {
return this.$store.getters.getFilteredProcedures();
},},
Vuex代码:
async likeProcedure({ dispatch },postId) {
const userId = fb.auth.currentUser.uid;
// update user object
await fb.usersCollection.doc(userId).update({
[`likedProcedures.${postId.id}`]: true,});
dispatch("fetchUserProfile",{ uid: userId });
},
旁注:我正在尝试删除dispatch("fetchUserProfile")
命令,但这没有用,因为那样的话我将不使用而调用dispatch
。而且我无法删除dispatch
,因为调用它的对象为空。而且我无法删除该对象,因为参数('postId')
无效。因此,如果有人知道如何处理,那将非常有帮助。
谢谢:)
解决方法
所以这是我提出的最好的解决方案。它破坏了单一事实来源的想法,但至少它提供了立即的UI更新:
async likeProcedure({ dispatch,state },postId) {
console.log("likeProcedure");
const userId = fb.auth.currentUser.uid;
// line below provides immediate update to state and hence to the UI
state.userProfile.likedProcedures[postId.id] = true;
// line below updates Firebase database
await fb.usersCollection.doc(userId).update({
[`likedProcedures.${postId.id}`]: state.userProfile.likedProcedures[
postId.id
],});
// line below then fetches the updated profile from Firebase and updates
// the profile in state. Kind of useless,but ensures that client and
// Firebase are in-sync
dispatch("fetchUserProfile",{ uid: userId });
},async fetchUserProfile({ commit },user) {
// fetch user profile
const userProfile = await fb.usersCollection.doc(user.uid).get();
// set user profile in state
commit("setUserProfile",userProfile.data());
// change route to dashboard
if (router.currentRoute.path === "/login") {
router.push("/");
}
},