Nyasha
Nyasha

Reputation: 101

Firebase React native Expo file upload and download issue resolving promise

I'm having a problem where the Array is not filled out, I think its something to do with the promoses resolving.

const UploadFile = async ({
  imageName = `${Date.now()}`,
  imageUris,
  imageFolder = '',
  metadata,
}: IFile) => {
 if (imageUris) {
    const promises: any[] = [];
    const imageURLs: string[] = [];

    imageUris.forEach(async (uri) => {
      const randomNumber = Randomize('0', 10);
      const finalImageName = `${Slugify(imageName)}`.toLowerCase();

      const imagePath = `${imageFolder}/${finalImageName}-${randomNumber}`;
      const imageRef = storageRef.child(imagePath);
      const blob = (await fetch(uri)).blob();

      const uploadTask = imageRef.put(await blob, metadata);

      uploadTask.on(
        firebase.storage.TaskEvent.STATE_CHANGED,
        (snapshot) => {
          const progress =
            (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
            console.log('Upload is ' + progress + '% done');
        },
        (error) => console.log('Error:', error),
        () => {
          uploadTask.snapshot.ref.getDownloadURL().then((downloadURL) => {
            console.log('File available at', downloadURL);
            imageURLs.push(downloadURL);
          });
        },
      );

      promises.push(uploadTask);
    });

    // Not sure promise is resolving
    Promise.all(promises).then((i) => {
      console.log('All files uploaded', i);
    });

    Promise.all(imageURLs).then((i) => {
      console.log('All imageURLs', i);
    });
  }
}

Output:

Retrieved listings
All files uploaded Array []
All imageURLs Array []
imageURLs Contents undefined
Upload is 0% done
Upload is 0% done
Upload is 100% done
File available at https://firebasestorage.googleapis.com/v0/b/wrecknet-ab69d.appspot.com/o/listings%2Fcar-5701393331?alt=media&token=ccfda911-36fb-4305-b6d7-0ee06fc824e1
Listing was successfully created
Upload is 100% done
File available at https://firebasestorage.googleapis.com/v0/b/wrecknet-ab69d.appspot.com/o/listings%2Fcar-4491812919?alt=media&token=03f72706-4201-4652-9172-8bcefaeb3e1f

As you can see the "All files uploaded Array []" and "All imageURLs Array []" arrays are empty, I suspect the Promise is not resolving.

Upvotes: 0

Views: 104

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 600141

As far as I know you can either listen to the on() of the UploadTask or to its then(), but not to both. Luckily you don't do anything meaningful in the on handling, so the entire code can be simplified down to:

const UploadFile = async ({
  imageName = `${Date.now()}`,
  imageUris,
  imageFolder = '',
  metadata,
}: IFile) => {
 if (imageUris) {
    const promises: any[] = [];

    imageUris.forEach(async (uri) => {
      const randomNumber = Randomize('0', 10);
      const finalImageName = `${Slugify(imageName)}`.toLowerCase();

      const imagePath = `${imageFolder}/${finalImageName}-${randomNumber}`;
      const imageRef = storageRef.child(imagePath);
      const blob = (await fetch(uri)).blob();

      promises.push(imageRef.put(await blob, metadata));
    });

    Promise.all(promises).then((imageURLs) => {
      console.log('All imageURLs', imageURLs);
    });
  }
}

Upvotes: 1

Related Questions