Firebase onSnapshot:取消订阅除进行更改的用户之外的所有用户的监听
Firebase onSnapshot: Unsubscribe from listening for all users except the one who made the changes
我正在使用 React js 来处理 firebase。
纠正我如果我错了请:
假设同一页面上有1000个用户,他们都在监听集合变化。如果其中之一,比方说给 post 一个赞,那么所有 1000 个用户都会向 firebase 发出读取请求? (经济上不友好)。
我想实现的:只监听对集合进行修改的用户的更改,并取消订阅其他人的监听,他们只有在重新加载页面时才会看到更改。
是否可以用 firebase 实现这样的逻辑?提前致谢
对于您的 use-case,您不应使用 Firestore 侦听器。您应该改为使用 useEffect
获取数据一次,并且仅在用户喜欢 post 时使用 setState()
更新组件。请参阅下面的示例代码:
const [value, setValue] = useState([])
const colRef = query(collection(db, "<collection>"))
// This will only get collection documents once.
// Needs to refresh/reload page to get updated data.
useEffect(() => {
const getDataOnce = async () => {
const querySnapshot = await getDocs(colRef);
renderData(querySnapshot)
}
getDataOnce()
}, [])
// Handles the click button which updates the state.
// Renders updated value to only user who triggered this async function.
async function handleClick() {
// Document reference to be updated.
const docRef = doc(db, "<collection>", "<document-id>")
// Updates the document reference.
await updateDoc(docRef, {
like: increment(1)
})
// Get the new updated data from the collection.
const querySnapshot = await getDocs(colRef)
// Sets the data to the `setValue` state.
renderData(querySnapshot)
}
// Sets the data to the setValue state.
function renderData(querySnapshot) {
setValue(querySnapshot.docs.map(doc => ({
id: doc.id,
data: doc.data()
})))
}
上面的示例代码只会获取进行修改的特定用户的更新数据。其他用户将不得不 reload/refresh 该页面以获取更新的数据。我还对示例代码留下了一些评论。
更多相关信息,您可以查看这些文档:
我正在使用 React js 来处理 firebase。
纠正我如果我错了请:
假设同一页面上有1000个用户,他们都在监听集合变化。如果其中之一,比方说给 post 一个赞,那么所有 1000 个用户都会向 firebase 发出读取请求? (经济上不友好)。
我想实现的:只监听对集合进行修改的用户的更改,并取消订阅其他人的监听,他们只有在重新加载页面时才会看到更改。
是否可以用 firebase 实现这样的逻辑?提前致谢
对于您的 use-case,您不应使用 Firestore 侦听器。您应该改为使用 useEffect
获取数据一次,并且仅在用户喜欢 post 时使用 setState()
更新组件。请参阅下面的示例代码:
const [value, setValue] = useState([])
const colRef = query(collection(db, "<collection>"))
// This will only get collection documents once.
// Needs to refresh/reload page to get updated data.
useEffect(() => {
const getDataOnce = async () => {
const querySnapshot = await getDocs(colRef);
renderData(querySnapshot)
}
getDataOnce()
}, [])
// Handles the click button which updates the state.
// Renders updated value to only user who triggered this async function.
async function handleClick() {
// Document reference to be updated.
const docRef = doc(db, "<collection>", "<document-id>")
// Updates the document reference.
await updateDoc(docRef, {
like: increment(1)
})
// Get the new updated data from the collection.
const querySnapshot = await getDocs(colRef)
// Sets the data to the `setValue` state.
renderData(querySnapshot)
}
// Sets the data to the setValue state.
function renderData(querySnapshot) {
setValue(querySnapshot.docs.map(doc => ({
id: doc.id,
data: doc.data()
})))
}
上面的示例代码只会获取进行修改的特定用户的更新数据。其他用户将不得不 reload/refresh 该页面以获取更新的数据。我还对示例代码留下了一些评论。
更多相关信息,您可以查看这些文档: