I've been trying to fix this issue from the last night and given that I'm a new dev, this is EXTREMELY frustrating.
I'm trying to display all the images in my firebase's storage on to the screen inside my Home.js
component. There are 8 imagees in total in my "images/"
folder in firebase storage. I wrote this code inside the Home
component:
export default function Home() {
var storageRef = firebase.storage.projectStorage.ref("images");
const [imagesArray, setImagesArray] = useState([]);
let tempImagesArray = [];
useEffect(() => {
storageRef
.listAll()
.then((res) => {
res._delegate.items.forEach(function (imageRef) {
//imageRef is containing the path to each image in the storage
projectStorage
.ref(imageRef._location.path_)
.getDownloadURL()
.then((url) => {
tempImagesArray.push(url);
setImagesArray((oldArr) => [...oldArr, url]);
});
});
})
.then((ress) => {
console.log(tempImagesArray.length); **// displays: 8 which is correct!**
console.log("state array is ", imagesArray); // returns an empty array
console.log("temp images array is ", tempImagesArray); // returns the CORRECT array containing URL links of all the images in the storage
})
.catch((err) => {
console.log(err);
});
//This array contains ALL the images in the images storage bucket. Now display it :)
}, []);
The weird part is that sometimes, usually if I refresh the page after a long time, the above code works and the imagesArray
contains 8 images but if I refresh it again - its all gone.
If for any reason, you cannot give me the solution of the above problem, can you give me a way in which I can somehow use tempImagesArray
which is NOT a state array to iterate over the links and show them to the user in the Home
Component?
PS: As far as setting the state array (imagesArray) is considered, I have tried two other methods to set it namely:
setImagesArray(tempImagesArray)
And
setImagesArray([...imagesArray, url])
PPS: Since someone duplicated this question - How is this question linked to the promises question that is said to already have an answer? I'm not trying to do stuff when all promises are resolved, I'm trying to set my array state correctly! How are these two even linked?