Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

197
Vistas
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?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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?

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda