Jim
Jim

Reputation: 2322

How to upload an image to firebase storage and then return the download url?

Im trying to upload an image to firebase storage in a react-native project, then return the download URL once upload is complete.

this is what I tried: EDITED:

const uploadImg = async (dispatch, uri, uid, mime = 'image/png') => {
    console.log('Starting image upload...');

    dispatch({ type: types.UPLOAD_IMG, info: 'Uploading profile image...' });
    const uploadUri = Platform.OS === 'ios' ? uri.replace('file://', '') : uri;

    return (imageRef = firebase
        .storage()
        .ref(uid)
        .child('profileImg')
        .putFile(uploadUri, { contentType: 'image/png' })
        .catch((err) => {
            uploadImgFail(dispatch, err.message);
        }));
};

part of implementation:

uploadImg(dispatch, img, userCredential.user.uid)
    .then((imgRef) => {
        const imgUrl = imgRef.getDownloadURL();
        console.log('uploaded Image URL: ' + imgUrl)
        uploadImgSuccess(dispatch, 'Profile image upload successful...');
        // rest of action
}

the problem is the download URL isn't returned by the function, I get unhandled promise rejection: "can't find variable: imgUrl"

Any help on achieving this with react-native-firebase?

Upvotes: 2

Views: 326

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317467

You will need to actually return a value from uploadImg. Right now it's returning nothing. Add a return keyword before imageRef.putFile() to return the promise that its chained promise returns.

Upvotes: 3

Related Questions