Recommand · October 14, 2021 0

Firebase 9 uploading photo

I tried to apply photo uploading for firebase 9 with the code:

const uploadTask = storage.ref(`images/${image.name}`).put(image);

and:

            storage
                .ref("images")
                .child(image.name)
                .getDownloadUrl()
                .then(url => { 
                    // post image inside the database
                    db.collection("posts").add({ 
                        timestamp: Firebase.ServerValue.TIMESTAMP,
                        caption: caption, 
                        imageUrl: url, 
                        username: username
                    });

                    // set progress back to 0 once it's done! and reset everything else 
                    setProgress(0);
                    setCaption("");
                    setImage(null);
                })

However, upon running my code, an error:
TypeError: firebase__WEBPACK_IMPORTED_MODULE_2_.storage.ref is not a function

How do I fix this?

The code you’ve shown looks correct for firebase 8, but you say you’re using version 9. Version 9 has some significant changes. So you’ll either need to roll back to version 8, or update your code to use the new patterns. For example, your first code snippet is now done like this:

import { getStorage, ref, uploadBytes } from "firebase/storage"

const storage = getStorage();
const storageRef = ref(storage, `images/${image.name}`);

const uploadTask = uploadBytes(storageRef);

You can see more information and examples here: https://firebase.google.com/docs/storage/web/upload-files

And instructions on how to upgrade can be found here: https://firebase.google.com/docs/web/modular-upgrade