0

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.

kzoeps
  • 396
  • 5
  • 15

1 Answers1

1

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: How to stop Firestore `get` query on componentWillUnmount

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807