-1

I'm currently working with Firebase to upload an image to the storage. I created an uploadImage function which takes an image and saves it to Firebase Storage then returns the url of that saved image. When the user clicks the Submit button, I use that uploadImage function to save that image and get back a url. The image is properly being saved, but the url that is being logged is undefined. I'm pretty sure it's an issue with the aysnc-await implementation I have. Any thoughts on this? Thank you!

UploadForm.js:

import { uploadImage } from "../firebase/functions";

const UploadForm = () => {
         const [image1, setImage1] = useState(null);

         const saveForm = async (file) => {
             const url1 = await uploadImage(image1);
             console.log("URL", url1); //the url here is UNDEFINED
          };

         return (
               <ImageUploadForm setImageProp={setImage1} />
        
               <button
                 onClick={(e) => {
                   e.preventDefault();

                   saveForm(image1);
                }}
               ></button>
          );

uploadImage function:

const uploadImage = async (file) => {
         const storageRef = storageService.ref().child("posts/" + file.name);
         
         storageRef.put(file).on(
            "state_changed",
            (snapshot) => {},
            (error) => {
               console.log(error);
            },
             async () => {
               return await storageRef.getDownloadURL();
            }
          );
    };

1 Answers1

1

Your uploadImage function doesn't return anything, just return the promise

return storageRef.put(file).on(

or, (since I don't know how that function works / what it returns), possibly

const uploadImage = (file) => {
   return new Promise((resolve, reject) => {
     const storageRef = storageService.ref().child("posts/" + file.name);
     
     storageRef.put(file).on(
        "state_changed",
        (snapshot) => {},
        (error) => {
           console.log(error);
           reject(error);
        },
        () => {
           const res = storageRef.getDownloadURL();
           resolve(res);
        }
      );
  };
}
Kevin B
  • 94,570
  • 16
  • 163
  • 180
dave
  • 62,300
  • 5
  • 72
  • 93
  • That worked, thanks – Jack Hanneway May 27 '21 at 18:43
  • I believe `async` functions always return a Promise (though you still need to define what you want to return as noted by the answer): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function – Reed Dunkle May 27 '21 at 18:48
  • 1
    they do, I'm not saying return *a* promise, I'm saying return *the* promise, as currently they were calling the promise but not returning it, so instead they were returning *a* promise which resolved to undefined. – dave May 27 '21 at 18:49