I am trying to display data retrieved from a sub-collection in firebase for my react app. I do know that there are other answers in stackoverflow. But the solutions does not help me in my scenario, like useState set method not reflecting change immediately.
As mentioned, I need to attain the data before the rendering of the page to prevent the page being loaded without the data. Shown in my getPortfolioData() this was not an issue and the data was set and displayed when the page load. But this was not the case for getImageData().
I tried the following below, and the outcome is that the data is only set after a repetition of 4-5 times on average, but it sets in the console but the display doesn't show it. But what I need is for it to be set and then render the display.
useEffect(() => {
getPortfolioData();
getImageData();
}, [imageData])
Main Codes:
function getImageData() {
setLoading(true);
database.portfolioRef
.doc(portfolioId)
.collection("images")
.get()
.then((snapshot) => {
const imageItems = [];
snapshot.docs.map((doc) => {
console.log(doc.data());
imageItems.push(doc.data());
});
console.log(imageItems);
setImageData(imageItems);
console.log(imageData);
}).catch((e) => console.log(e));
setLoading(false);
}
function getPortfolioData() {
database.portfolioRef
.doc(portfolioId)
.get()
.then((snapshot) => {
console.log(snapshot.data());
setPortfolioData(snapshot.data())
setLastModifiedBy(snapshot.data().lastModifiedBy)
setlastModifiedDate(snapshot.data().lastModifiedDate)
}).catch((e) => console.log(e));
}
useEffect(() => {
getPortfolioData();
getImageData();
}, [])
SOLVED (Answer below)
async function getVideoData() {
setLoading(true);
setVideoMessage("")
try {
const snapshot = await database.portfolioRef.doc(portfolioId).collection("videos").get();
if (snapshot !== null) {
var videoItems = [];
snapshot.docs.map((doc) => {
console.log(doc.data());
videoItems.push(doc.data());
});
setVideoData(videoItems);
} else {
setVideoMessage("There is not existing videos for this portfolio.")
console.log("else" + videoMessage);
}
} catch {
setVideoMessage("There is not existing videos for this portfolio.")
console.log("catch" + videoMessage);
}
setLoading(false);
}