0

This is my useEffect() :

const [imagesArray, setImagesArray] = useState([]);

useEffect(() => {
    console.log("rendering");
    let tempImagesArray = [];
    storageRef
      .listAll()
      .then((res) => {
        res._delegate.items.forEach(function (imageRef) {
          projectStorage
            .ref(imageRef._location.path_)
            .getDownloadURL()
            .then((url) => {
              //url is the URL of an image in the database. I have checked, IT is correct
              tempImagesArray.push(url);
            });
        });
      })
      .catch((err) => {
        console.log(err);
      });
    setImagesArray([...imagesArray, ...tempImagesArray]);
    console.log("Temp images arr is", tempImagesArray); //["https://firebase....","https://firebase....", "https://firebase...."]
    console.log("Main images state arr is ", imagesArray); //[]
  }, []);

I'm adding URLs to tempImagesArray and after I have added all URLs, I try to update the imagesArray using setImagesArray but when I console log imagesArray, it shows an empty array AND if I console log tempImagesArray it shows an array which is full of URLs!!!

Why is this happeneing and how do I fix this? Please help, I have been trying to solve this for hours

K Kimash
  • 87
  • 1
  • 2
  • 9
  • Try moving setImagesArray([...imagesArray, ...tempImagesArray]); just below of tempImagesArray.push(url); Tell me if it works – fjplaurr May 12 '21 at 10:20
  • The `then` callback will run after you have already called `setImagesArray`. You cannot expect to get a value *now* when it is only available in the *future*. – trincot May 12 '21 at 10:21
  • 1
    `setImagesArray` is asynchronous function so when you try to access `imagesArray` after immediately changing it will return previous value which in your case is blank array. So try to use `useEffect` – Priyank Kachhela May 12 '21 at 10:21
  • 1
    @fjplaurr IT WORKED!!! You are a savior – K Kimash May 12 '21 at 10:23
  • @PriyankKachhela how is setImagesArray asynchronnous? Its not fetching anything! It's just changing the state! – K Kimash May 12 '21 at 10:24
  • What was happening is that all the block storageRef... is being executed asynchronously. That means that, by the time setImagesArray arrives, temImagesArray is still empty. That's why yo have to move it just where I said to make sure that they are executed synchronously, one after the other. – fjplaurr May 12 '21 at 10:25
  • Please follow this answer: https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately – Priyank Kachhela May 12 '21 at 10:26

0 Answers0