Coolkid
Coolkid

Reputation: 517

Randomise image order from Firebase storage

i'm have a webapp with images on one of the pages. Storage i use Firebase and to optimise, i use Imagekit. Code is React and Javascript. I noticed that when i use Firebase Storage function listAll() to render all images, everytime i refresh, the image order is different.

useEffect(() => {
    listAll(imageListRef.current).then((response) => {
      response.items.forEach((item) => {
        // console.log(item);
        getDownloadURL(item).then((url) => {
          setImageList((prev) => [...prev, url]);
        });
      });
    });
  }, []);


Screenshots of my refreshes: Screenshot1 Screenshot2

Why is the image order changed on every refresh?

Upvotes: 1

Views: 51

Answers (1)

aabdulahad
aabdulahad

Reputation: 1123

getDownloadUrl() is an asynchronous function call, which will resolve in a different order each time for each file. The best way to solve this would be to initialise an array and then to store the image URI in the array index that you are currently iterating through.

e.g.

listAll(imageListRef.current).then((response) => {
  let list = new Array()
  response.items.forEach((item, index) => {
    getDownloadURL(item).then((url) => {
      list[index] = url;
    });
  });
  setImageList(list)
});

Upvotes: 1

Related Questions