Adding download url from firebase storage to firestore

Viewed 48

I want to push my array with download urls that i get after uploading my images to firestore, I have my urls in an array and I can log them to console, but when I create my document in firestore and set imgs property to my images array, I will se empty array in firestore. here we have my code when uploading imgs:

tavlinForm.addEventListener('submit', (e) => {
          e.preventDefault();

          const filesLit = document.querySelector('#image').files;

          const files = Array.from(filesLit);

          files.forEach((file) => {
            let imageRef = ref(storage, 'images/' + file.name);
            const metadata = file.type.split('/')[0];
            const uploadTask = uploadBytesResumable(
              imageRef,
              file,
              metadata
            );

            if (metadata === 'image') {
              uploadBytes(imageRef, file).then((snapshot) => {
                console.log('Uploaded a blob or file!');

                getDownloadURL(imageRef).then((url) => {
                  imagesArry.push(url);
                  console.log(imagesArry);
                });
              });
            }
          });

          addDoc(colRef2, {
            title: tavlinForm.title.value,
            location: tavlinForm.location.value,
            disc: tavlinForm.disc.value,
            junior: {
              first: tavlinForm.junior_f.value,
              second: tavlinForm.junior_s.value,
              third: tavlinForm.junior_t.value,
            },
            lady: {
              first: tavlinForm.lady_f.value,
              second: tavlinForm.lady_s.value,
              third: tavlinForm.lady_t.value,
            },
            imgs: imagesArry,
            createdAt: serverTimestamp(),
          }).then(() => {
            console.log(imagesArry);
            tavlinForm.reset();
          });
        });

and imagesArray is a global array in the top of my js file. How can I make sure that the uploadBytes() is running first and only after that addDoc() is running?

0 Answers
Related