Firebase multiple image upload then call function

Viewed 77

I am successfully batch uploading images to firebase, but for some reason, my data is not being uploaded afterwards.

I can confirm though, it does work perfectly ONLY on a fresh build for the first time? Super weird.

I am not sure what is going wrong as I am able to receive the urls fine after the fact.

Here is my function:

  onUploadImages = () => {
    let photo =
      Platform.OS === 'ios'
        ? this.state.images.map(img => img.uri.replace('file://', ''))
        : this.state.images.map(img => img.uri);

    Promise.all(
      photo.map((image, index) => {
        const sessionId = new Date().getTime();
        const Blob = RNFetchBlob.polyfill.Blob;
        const fs = RNFetchBlob.fs;
        window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest;
        window.Blob = Blob;
        let uploadBlob = null;
        let mime = 'image/jpg';

        const imageRef = firebase
          .storage()
          .ref('brandProducts/')
          .child(`${this.props.userData.uid}`)
          .child(`${sessionId}-${index}`);

        return fs
          .readFile(image, 'base64')
          .then(data => {
            return Blob.build(data, {
              type: `${mime};BASE64`,
            });
          })
          .then(blob => {
            uploadBlob = blob;
            return imageRef.put(blob, {contentType: mime});
          })
          .then(() => {
            uploadBlob.close();
            return imageRef.getDownloadURL();
          });
      }),
    )
      .then(results => {
        //results is, here, [ urlFromFirst, urlFronSecond, ...]
        const urls = {...this.state.urls};
        results.forEach((r, i) => (urls[i] = r));
        const postObj = {
          ...this.state.postObj,
          urls,
        };
        //THIS WONT RUN (BUT I AM ABLE TO LOG PROPER postObj) here
        return firebase
          .firestore()
          .collection('brandProducts')
          .add(postObj);
      })
      .then(docRef => {
        Actions.categories();
        console.log('Document written with ID: ', docRef.id);
      })
      .catch(error => {
        console.error(error);
      });
  };

Here is my postObj:

postObj: {
  title: 'A Title',
  price: 20,
  description: 'Some text here',
  webLink: 'a url as a string',
  user: 'Username',
  urls: {
    '0': 'downloadUrl1',
    '1': 'downloadUrl2',
    '2': 'downloadUrl3',
  }
},

I would appreciate any help i can get figuring out where this is going wrong. Cheers!

0 Answers
Related