M Y
M Y

Reputation: 131

Error when trying to upload blob to Firebase Storage (React Native)

I have an image picker component in my React-Native app that allows users to choose an image. This is then saved to this.state.imageUri. My goal is to upload the image to Firebase Storage and then link it to Realtime Database so that it can be accessed in relation to a specific list item. I am using two functions for this:

uriToBlob = (uri) => {
    console.log('uri: ' + uri)
    return new Promise(function(resolve, reject) {
      try {
          var xhr = new XMLHttpRequest();
          xhr.open("GET", uri);
          xhr.responseType = "blob";
          xhr.onerror = function() {reject("Network error.")};
          xhr.onload = function() {
              if (xhr.status === 200) {resolve(xhr.response)}
              else {reject("Loading error:" + xhr.statusText)}
          };
          xhr.send();
      }
      catch(err) {reject(err.message)}
    })
  }

and

uploadToFirebase = (blob) => {
    console.log('uploading to firebase')
    return new Promise((resolve, reject)=>{
      var storageRef = firebase.storage().ref();
      storageRef.child('uploads/photo.jpg').put(blob, {
        contentType: 'image/jpeg'
      }).then((snapshot)=>{
        blob.close();
        resolve(snapshot);
      }).catch((error)=>{
        reject(error);
      });
    });
  }

Upon a button being pressed, I run this code:

this.uriToBlob(this.state.imageUri).then(function(blob) {
      return this.uploadToFirebase(blob)
    });

However, I always get the error

[Unhandled promise rejection: TypeError: undefined is not an object (evaluating 'this.uploadToFirebase')]

I have not worked with Firebase Storage or blobs before, so I would greatly appreciate some insight as to why this does not work. Thank you!

Upvotes: 0

Views: 720

Answers (1)

monsty
monsty

Reputation: 633

The problem is located here :

this.uriToBlob(this.state.imageUri).then(function(blob) {
  return this.uploadToFirebase(blob)
});

You are not using arrow function, so "this" is actually not the context you are looking for (the one from the parent scope).

You should do this instead :

this.uriToBlob(this.state.imageUri).then((blob) => {
  return this.uploadToFirebase(blob);
});

Upvotes: 1

Related Questions