如何在 web v9 中取消 Firestore 调用?

huangapple go评论76阅读模式
英文:

How to cancel firestore calls in web v9?

问题

我有一个React和Firestore应用程序。该应用程序从Firestore获取数据并在表格中显示。数据的获取是在useEffect中完成的,如下所示。

export default DisplayPage() {
  const [records, setRecord] = useState([]);
  useEffect(() => {
    const getData = async () => {
      const docRef = doc(db, 'table_name');
      return getDoc(docRef);
    }
    getData().then(data => setRecord(data.data()))
    return () => {
        // 在这里实现取消调用?
    }
  })
  // 表格显示部分...
}

它工作得非常好,但我在这里遇到的问题是如何取消Firestore的调用。一旦我访问页面,API调用就会被触发,但即使在调用完成之前返回到其他页面,API调用仍然会继续进行,直到它们完成。我知道fetch有AbortController,Axios也有,但我无法找到Firestore调用的取消方法。我已经看到了对onSnapshot监听的取消方法,但在阅读Firestore普通获取调用的文档时,并没有找到取消调用的选项。

英文:

I have a react, firestore app. The app gets data from firestore and displays it in a table. The fetching of the data is done in a useEffect as can be seen below.

export default DisplayPage() {
  const [records,setRecord] = useState([]);
  useEffect(() => {
    const getData = async () => {
      const docRef = doc(db, 'table_name');
      return getDoc(docRef);
    }
    getData().then(data => setRecord(data.data()))
    return () => {
        // implement cancel call here?
    }

  })
  // table display here ...
}

It works all fine and good but the problem I have here is how do I cancel the firestore calls. As soon as I visit the page the API calls are called but even if i navigate back to a page before the calls are completed, the API calls keep continuing until they've finished. I know fetch has AbortController and so does Axios but I was unable to find anything for Firestore calls. I have seen it for onSnapshot listens but upon reading the docs for normal firestore get calls there aren't any options for cancelling the call.

答案1

得分: 1

没有办法取消已经开始的get()调用。我能想到的最好方法是检测组件是否已经超出范围,当发生这种情况时不调用setRecord

在快速搜索中,这正是以下答案展示的内容:https://stackoverflow.com/questions/52524368/how-to-stop-firestore-get-query-on-componentwillunmount

还请参考:

英文:

There is no way to cancel a get() call that has already started. The best I can think of is to detect that the component has gone out of scope, and not calling setRecord when that has already happened.

Upon a quick search, that's precisely what the answer here shows: https://stackoverflow.com/questions/52524368/how-to-stop-firestore-get-query-on-componentwillunmount

Also see:

huangapple
  • 本文由 发表于 2023年3月4日 05:50:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/75632169.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定