'Getting the download URL of an uploaded image synchronously in Firebase Storage

I'm using Firestore and Storage in a React Native project and I'm working on a feature that migrates SQLite data into Firebase. Once the user signs in for the first time, the migration process runs synchronously. Among the data to migrate there are base64 images and no matter what I do, despite using async/await everywhere, I get the DownloadURL "too late", after the migration process is done and the new data from Firestore is listed. So, I cant show the images at first, I have to reload the app.

My code:

const upload64BaseImage = async (photo, docRef) => {
  try {
    //fetch doesn't work with base64 images and Firebase Cloud Storage
    const blob = await new Promise((resolve, reject) => {
      const xhr = new XMLHttpRequest();
      xhr.onload = function () {
        resolve(xhr.response);
      };
      xhr.onerror = function (e) {
        console.log(e);
        reject(new TypeError("Network request failed"));
      };
      xhr.responseType = "blob";
      xhr.open("GET", photo, true);
      xhr.send(null);
    });

    const imageRef = ref(storage, `images/${docRef}.jpg`);
    const metadata = {
      contentType: "image/jpeg",
    };

    const snapshot = await uploadBytes(imageRef, blob, metadata);
    const downloadUrl = await getDownloadURL(snapshot.ref);
    
    return downloadUrl;
  } catch (error) {
    console.log(`error`, error.message);
  }
};

const createNewDocument = async (userId, data) => {
  try {
    const newUserRef = doc(collection(db, "users"));
    const myTimestamp = Timestamp.fromDate(new Date(data.Birthdate));
    const downloadUrl = await upload64BaseImage(data.Photo, newUserRef.id);

    //crear un objeto
    const newUserObjetc = {
      UserId: userId,
      Birthdate: myTimestamp,
      Name: data.Name,
      Surname: data.Surname,
      Photo: downloadUrl || null,
    };

    await setDoc(newUserRef, newUserObjetc);

    return newUserRef.id;
  } catch (error) {
    console.log(`error`, error.message);
  }
};


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source