expo react native upload image to firebase storage

Viewed 336

I am trying to upload an image from the phone library with expo-image-picker to Firebase storage and download the URL to save it in Firestore but for some reason, my app keeps crashing on (iPhone) without any error. I have tried every possible way to fix this issue(running my code line by line etc) but nothing has yet fixed this issue.

Has anyone encountered a similar issue and could help me with this particular problem? I have been stuck for a few days now. It would be a big help. Thank you in advance.

Here is my code:

Turning image to blob. at First, I used the fetch method but this seems to work better.

const urlToBlob = async (url) => {
  return await new Promise((resolve, reject) => {
    var xhr = new XMLHttpRequest();
    xhr.onerror = reject;
    xhr.onreadystatechange = () => {
      if (xhr.readyState === 4) {
        resolve(xhr.response);
      }
    };
    xhr.open("GET", url);
    xhr.responseType = "blob"; // convert type
    xhr.send();
  });
};

Uploading an image to storage. Sometimes it uploads but if you upload again it crashes.

const uploadImageAsync = async (imageUri) => {
  let blob;
  const imageRef = imageUri.substring(imageUri.lastIndexOf("/"));

  try {
    blob = await urlToBlob(imageUri);
    const ref = await firebase.storage().ref().child(imageRef);
    await ref.put(blob);
    return await ref.getDownloadURL();
  } catch (error) {
    console.log(
      " ~ file: eventServices.jsx ~ line 33 ~ createEvent ~ error",
      error
    );
  } finally {
    blob.close();
    console.log("blob closed");
  }
};

Here I get the image and pass it to my function which should return the URL to the image. URL then should get saved in Firestore.

export const createEvent = async (eventObj) => {
  const imageUri = eventObj.image;

  try {
    const downloadUrl = uploadImageAsync(imageUri);
    console.log(downloadUrl );
      await firebase
        .firestore()
        .collection("events")
        .add({ ...eventObj, image: downloadUrl });
      console.log("Event added!");
  } catch (error) {
    console.log(
      " ~ file: eventServices.jsx ~ line 62 ~ createEvent ~ error",
      error
    );
  }
};
0 Answers
Related