英文:
Firebase update function performs recursively
问题
这是你提供的代码的翻译部分:
function like(id) {
firebase.database().ref("memes/" + id).on("value", (snap) => {
const cs = snap.val().likes || [{
name: ""
}];
let res = [...cs, JSON.parse(localStorage.getItem("user"))].filter(item => item);
console.log(res);
firebase.database().ref("memes/" + id).update({
likes: res,
});
});
}
<p><button onclick="like('${y.name}/${y.head}')"><ion-icon name="thumbs-up"></ion-icon></button><b>${1 || y.likes.length }</b></p>
问题是,当我点击按钮时,like函数会递归执行,不断在RealTime数据库中的likes字段(一个数组)中添加对象。
就像这样:
likes:
0-> object
1-> object
....
英文:
I am making a website of where people can upload memes but I'm currently stuck at updating likes of meme
Here's the code
Js
function like(id) {
firebase.database().ref("memes/" + id).on("value", (snap) => {
const cs = snap.val().likes || [{
name: ""
}]
let res = [...cs, JSON.parse(localStorage.getItem("user"))].filter(item => item)
console.log(res)
firebase.database().ref("memes/" + id).update({
likes: res,
});
})
}
html
<p><button onclick="like('${y.name}/${y.head}')"><ion-icon name="thumbs-up"></ion-icon></button><b>${1 || y.likes.length }</b></p>
Problem is when I click on button the like function performs like recursively and just keeps adding objects in like field which is array in RealTime database .
Like this:
likes:
0-> object
1-> object
....
答案1
得分: 1
你正在使用以下代码打开一个监听器来监听 memes/{id}/
:
firebase.database().ref("memes/" + id).on("value",(snap) => {
所以每次更新时,你都会得到另一个回调,这就是为什么它不断递归添加项目。
你可以将其替换为 once
,这应该解决你的问题。
参考链接:https://firebase.google.com/docs/database/admin/retrieve-data#section-reading-once
关于 on value
的解释:
https://firebase.google.com/docs/database/admin/retrieve-data#value
value
事件用于读取给定数据库路径上的内容的静态快照,这些内容在读事件发生时存在。它在初始数据上触发一次,然后在数据更改时再次触发。
英文:
You are opening a listener to memes/{id}/
with the code:
firebase.database().ref("memes/" + id).on("value",(snap) => {
So every time you update you get another callback and that's why it keeps recursivelly adding items.
You can replace it with once
and that should solve your problem.
Reference: https://firebase.google.com/docs/database/admin/retrieve-data#section-reading-once
Explanation for the on value:
https://firebase.google.com/docs/database/admin/retrieve-data#value
> The value event is used to read a static snapshot of the contents at a given database path, as they existed at the time of the read event. It is triggered once with the initial data and again every time the data changes.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论