Linking images from Firebase Storage to Firestore document and displaying them in React Native

Linking images from Firebase Storage to Firestore document and displaying them in React Native

I understand that your goal is to generate, for each image that is uploaded to Cloud Storage, a Firestore document which contains a download URL.

If this is correct, one way is to use a Cloud Function that is triggered each time a new file is added to Cloud Storage. The following Cloud Function code does exactly that. You may adapt it to your exact requirements.

exports.generateFileURL = functions.storage.object().onFinalize(async object => {

    try {
        const bucket = admin.storage().bucket(object.bucket);
        const file = bucket.file(object.name);

        // You can check that the file is an image

        const signedURLconfig = { action: read, expires: 08-12-2025 };  // Adapt as follows

        const signedURLArray = await file.getSignedUrl(signedURLconfig);
        const url = signedURLArray[0];

        await admin.firestore().collection(profilePictures).add({ fileName: object.name, signedURL: url }) // Adapt the fields list as desired 
        return null;

    } catch (error) {
        console.log(error);
        return null;
    }

});

More info on the getSignedUrl() method of the Admin SDK here.

Also note that you could assign the Firestore document ID yourself, instead of having Firestore generating it as shown in the above code (with the add() method). For example, you can add to the image metadata the uid of the user and, in the Cloud Function,get this value and use this value as the Document ID.

Another possibility is to name the profile image with the users uid.

Linking images from Firebase Storage to Firestore document and displaying them in React Native

Leave a Reply

Your email address will not be published.