Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

108
Views
Not able to update the array state in a async Promise call inside on a upload image in react application using firebase

I am trying to upload multiple images on Firebase and get the URLs of each image and push them onto the database using api calls (With redux). I am trying to implement it using Promise.all() but the urls are being fetched asyncronously and the Promise.all() call is executed before the array state gets updated. Here is the code that might help you understand better.

.......... 
const [imgs,setImgs] = useState([])
const [urls,setUrls] = useState([]);
..........

//Code for setImg that will add all the files that are been selected!
..........

const uploadImages = async () => {
    const promises = [];
    imgs.map((image) => {
      const imageRef = ref(storage, `Drives/${image.name + v4()}`);
      const uploadTask = uploadBytesResumable(imageRef, image);
      promises.push(uploadTask);

      uploadTask.on(
        "state_changed",
        (snapshot) => {
          const progress = Math.round(
            (snapshot.bytesTransferred / snapshot.totalBytes) * 100
          );
          // dispatch(fetchStart());
        },
        (error) => {
          alert(error);
        },
        () => {
          getDownloadURL(uploadTask.snapshot.ref).then((url) => {
            console.log(url); // this is been shown after the promise.all is executed!!
            setUrls((oldArray) => [...oldArray, url]); // This is not getting updated as expexted!!
          });
        }
      );
    });

    Promise.all(promises) // Being executed before the urls state is updated hence is submitting a empty array!!
      .then(() => {
        toast.success("All images uploaded");
        const FormatDate = moment(data.date).format("DD/MM/YYYY");
        const { __v, ...rest } = data;
        if (urls.length === 0) {
          toast.error("Urls were not Pushed!!");
          console.log(urls);
          dispatch(clearState());
          return 0;
        }
        const formData = {
          ...rest,
          date: FormatDate,
          driveImages: [...urls] ,// Or urls ---- This is showing empty.. But after some time urls is being updated!!
          flags: {
            isUploadImage: true,
          },
        };
        dispatch(updateDrives(formData));
      })
      .catch((err) => toast.error(err));
  };

I have mentioned appropriate comments in the code for better understanding.

The versions of firebase that I am using is "firebase": "^9.7.0".

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

From what I understood, there are some key points to check in your code:

  1. Have you put uploadImages() function in a useEffect with a dependency of imgs to make sure imgs is not empty itself and the function will get called when imgs gets updated?

      useEffect(()=>{uploadImages()},[imgs]);
    
  2. When it comes to promises, keep in mind that there are two general approaches: using async/await or then()/catch(). Use one approach. If you are using async, you should use await before calling functions returning a promise.

  3. map() function in js always should return a result in each iteration. If you don't return anything all you get is an array with undefined values no matter what you have done in each iteration.

     const promiseArray = imgs.map(async () => {
     try{
       const uploadTask = await uploadBytesResumable(imageRef, image);
       ...
       return uploadTask;
        } catch(err){ 
          // handle err
        };
    });
    
    const result = await Promise.all(promiseArray);
    

If you don't want to return a value, use forEach() instead.

about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!