Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

106
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda