'Firestore data doesn't show up
In my custom hook, I am getting all the images in firestore collection. That was working fine UNTIL I have tried to get also metadata's of images. When I added the getMetaData function, I can't set the data to state even the datas seem fine in an array. See the code please.
import { useState, useEffect } from "react";
import { firebaseFireStore } from "../firebase/config";
import { storage } from "../firebase/config";
import { ref, getMetadata } from "firebase/storage";
const useFirestore = (collection) => {
const [docs, setDocs] = useState([]);
useEffect(() => {
const unsub = firebaseFireStore
.collection(collection)
.onSnapshot((snap) => {
let documents = [];
snap.forEach((doc) => {
const forestRef = ref(storage, doc.data().url);
getMetadata(forestRef)
.then((metadata) => {
documents.push({ ...doc.data(), metadata, id: doc.id });
return documents;
})
.catch((error) => {
console.log(error);
});
});
setDocs(documents);
console.log(docs); // [] EMPTY ARRAY, PROBLEM IS HERE.
console.log(documents); // [] length:13 data is complete inside.
});
return () => unsub();
// this is a cleanup function that react will run when
// a component using the hook unmounts
}, []);
return { docs };
};
export default useFirestore;
So, even if documents array has the data with metadata in it, it can't be set to state of docs. Any help appreciated.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
