AllinTheSauce
AllinTheSauce

Reputation: 63

Creating a storage reference to upload a image to Google Firebase

I am currently taking an older project which uses an outdated version of Firebase, and migrating it to the newest modular version. After following the documentation on the Firebase website, I've been able to get most of it done except for the following feature of my project: Allowing a logged in user to upload a photo.

Everything works besides my handleUpload function which looks like this:

const handleUpload = () => {
    const uploadTask = storage.ref('images/${image.name}').put(image);
    uploadTask.on(
        "state_changed",
        (snapshot) => {
            //Progress function ... (shows the load bar)
            const progress = Math.round(
                (snapshot.bytesTransferred / snapshot.totalBytes) * 100
            );
            setProgress(progress);
        },
        (error) => {
            //Error Function...
            console.log(error);
            alert(error.message);
        },
        () => {
            //complete function
            storage.ref("images").child(image.name).getDownloadURL()
            .then(url => {
                db.collection("posts").add({
                    timestamp: serverTimestamp,
                    caption: caption,
                    imageUrl: url,
                    username: username
                });
                setProgress(0);
                setCaption("");
                setImage(null);
            })
            

        }
    )
}

I can't seem to get this portion to work because Im having an issue turning the old firebase syntax into the newer modular version. I've tried to follow the online documentation by doing something like const storageRef = ref(storage, 'some-child'); but the rest still won't work.

Any ideas on how to fix this or what the function should look like with the newer syntax?

Upvotes: 2

Views: 512

Answers (1)

Dharmaraj
Dharmaraj

Reputation: 50830

The Modular version of the same should be as follows:

  1. First using ref() to create a StorageReference.
  2. Then creating an UploadTask using uploadBytesResumable(). Do note that just uploadBytes() cannot be used if you want to monitor upload progress.

Apart from that, functions within .on() listener same as V8.

import { getStorage, ref, uploadBytesResumable, getDownloadURL } from "firebase/storage";

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

  const uploadTask = uploadBytesResumable(storageRef, image);

  uploadTask.on(
    "state_changed",
    (snapshot) => {
      //Progress function ... (shows the load bar)
      const progress = Math.round(
        (snapshot.bytesTransferred / snapshot.totalBytes) * 100
      );
      // setProgress(progress);
    },
    (error) => {
      //Error Function...
      console.log(error);
    },
    async () => {
      //complete function
      // const url = await getDownloadURL(storageRef)
    }
  )
}

Then to add a document you need to use addDoc() function as shown below:

import { getFirestore, collection, addDoc } from "firebase/firestore"; 

const db = getFirestore();

const docRef = await addDoc(collection(db, "posts"), {...data});

Also checkout this answer for more details of changes in Firestore'ss syntax:

Firestore: What's the pattern for adding new data in Web v9?

Upvotes: 1

Related Questions