英文:
Firebase: When to use onSnapshot
问题
I understand your request to only provide translations for the code portions of your text. Here are the translated code sections:
// Original: const someValue = "Some other string"
const someValue = "另一些字符串"; // 例如,通过表单设置该值
// Original: db.collection("SomeCollection").doc("SomeDoc").update({data:someValue});
db.collection("某个集合").doc("某个文档").update({data: someValue});
// Original: someData = someValue;
someData = someValue;
Please note that I've translated the code comments and string values as requested.
英文:
So I know that you should keep the frontend and backend in sync using onSnapshot
if the user is looking at a page that can be updated by other users for example. But let's say the user is looking at a page that only he can update, like a page displaying some personal information.
Let's say I have this string let someData = "Some string"
that gets rendered on that page only one user can update. Now that user wants to update the data in that string. So a firestore document might get updated like this:
const db = firestore();
const someValue = "Some other string" //This value is set through a form for example
db.collection("SomeCollection").doc("SomeDoc").update({data:someValue})
Now that data change should obviously get displayed in the UI.
Here is my question. Given the fact that only the user can see the data on this page, what is the correct way to update the UI?
const db = firestore();
db.onSnapshot(snapshot=>someData = snapshot.data().data);
const someValue = "Some other string" //This value is set through a form for example
db.collection("SomeCollection").doc("SomeDoc").update({data:someValue});
OR
const db = firestore();
const someValue = "Some other string" //This value is set through a form for example
db.collection("SomeCollection").doc("SomeDoc").update({data:someValue});
someData = someValue;
What I mean is should I update the UI independently of the database or as a response to a document change to the database.
Hope I could make my question clear. Thanks in advance!
答案1
得分: 1
如果您已将快照监听器附加到文档,并编写代码来更新该文档,监听器将立即被调用(甚至在更改在服务器上发生之前)。在监听器之外不应该需要更新用户界面 - 只需让监听器立即响应更新并自行更新用户界面。
英文:
If you have a snapshot listener attached to a document, and you write code to update that document, the listener will get immediately invoked (even before the change happens on the server). There should be no need to update the UI outside of the listener - just let the listener respond to the update immediately and update the UI itself.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论