I have a web application that is built in Nextjs and uses Firebase Firestore for storing data. Everything else is fine with the app, but tools that test website speed give it horrible grades, because requests to Firestore never finish even though the app has already gotten all the data it needs on the frontend.
My code for fetching data:
const getData = () => {
const q = query(collection(firestore, "data"), where("published", "==", true));
const data = [];
const unsubscribe = onSnapshot(q, (querySnapshot) => {
querySnapshot.forEach((doc) => {
data.push({id: doc.id, ...doc.data()});
});
});
return data
}
The function for returning data works fine and everything is returned quickly, but the request keeps hanging without finishing. I've attached a screenshot captured from Chrome devtools. Image: "CAUTION: request is not finished yet!" How do I get Firestore to stop listening for changes in the database?
I've tried looking for solutions everywhere online and found some people saying that using "const unsubscribe = ..." to define the query and later calling "unsubscribe();" would work, but calling "unsubscribe();" prevents the function from returning the data at all for some reason.
If you want to fetch data only once, then use getDocs() instead:
const getData = async () => {
const q = query(collection(firestore, "data"), where("published", "==", true));
const querySnapshot = await getDocs(q);
return querySnapshot.docs.map(doc => ({id: doc.id, ...doc.data()}))
}
Unlike onSnapshot(), getDocs() won't listen for realtime updates. You can just call getData() again to reload the data. You can learn more about fetching data from Firestore in the documentation.