Home > OS >  Cannot get data out of composable to fetch firebase data
Cannot get data out of composable to fetch firebase data

Time:12-18

I have a composable in vue that uploads data to firebase storage. It works, but I cannot get the data out of the composable. I think it has something to do with a return or where I'm defining terms?

The code below is built around the documentation available for firebase Storage (https://firebase.google.com/docs/storage/web/upload-files).

useStorage.js

import { ref } from "vue";
import { projectStorage } from "../firebase/config";
import {
  uploadBytesResumable,
  getDownloadURL,
  ref as storageRef,
} from "@firebase/storage";

const useStorage = () => {
  const error = ref(null);
  const url = ref(null);
  const filePath = ref(null);

  const uploadImage = async (file) => {
    filePath.value = `images/${file.name}`;

    const storageReference = storageRef(projectStorage, 
 filePath.value);

    const uploadTask = 
 uploadBytesResumable(storageReference, file);

    await uploadTask.on(
      "state_changed",
      (snapshot) => {
        const progress =
          (snapshot.bytesTransferred / snapshot.totalBytes) 
 * 100;
        console.log("Upload is "   progress   "% done");
      },
      (err) => {
        console.log(err);
        error.value = err.message;
      },
      () => {
 
        
 getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) 
 => {
          console.log("File available at", downloadURL);
          url.value = downloadURL;
          console.log(url.value); <--HAS CORRECT VALUE
          return url.value; <--DOESNT DO ANYTHING
        });
      }
    );
    console.log(url.value);
  };

   return { url, filePath, error, uploadImage }; <--URL IS 
NOT RETURNING OUT OF THIS COMPOSABLE
};

export default useStorage;

CodePudding user response:

A simpeler approach would be to await getDownloadUrl: url.value = await getDownloadURL(uploadTask.snapshot.ref). Then, you can get rid of the .then on that function. Right now, return url.value is assigned to nothing.

Warning: Also write some sort of catch - in case something would go wrong - in a production environment.

  • Related