Search code examples
react-nativefirebase-storagereact-native-firebase

@react-native-firebase/storage - get url after uploading an image


Im trying to find an efficient way to get the url of an image in firebase right after ive uploaded it. Id like to avoid writing a totally separate function to this....and instead Id like to include it in the promise chain. See code below

import storage from '@react-native-firebase/storage';

storage()
        .ref('path/to/remote/folder')
        .putFile('uri/of/local/image')
        .then(() => {
          //Id like to use getDownloadUrl() function here;
        })

Solution

  • You can create chain of promises using await and then easily get your download url as below :

    /**
     * Upload the image to the specific firebase path
     * @param {String} uri Uri of the image
     * @param {String} name Name of the image
     * @param {String} firebasePath Firebase image path to store
     */
    const uploadImage = async (uri, name, firebasePath) => {
      const imageRef = storage().ref(`${firebasePath}/${name}`)
      await imageRef.putFile(uri, { contentType: 'image/jpg'}).catch((error) => { throw error })
      const url = await imageRef.getDownloadURL().catch((error) => { throw error });
      return url
    }
    

    Now you can call this function as below :

    const uploadedUrl = await uploadImage('uri/of/local/image', 'imageName.jpg', 'path/to/remote/folder');
    

    Now uploadedUrl will contains url of the uploaded image.