Home > Software design >  Firebase Storage TypeScript error: Property 'on' does not exist on type 'Promise<U
Firebase Storage TypeScript error: Property 'on' does not exist on type 'Promise<U

Time:11-21

I'm trying to implement a Vue Composable that uploads files to Firebase storage.

I am using the modular Firebase version 9 and implementing it by copying this example in their docs.

But that example uses plain JavaScript, and I want to implement it in TypeScript.

In my code below .on is throwing a TypeScript error that says Property 'on' does not exist on type 'Promise<UploadResult>'.

How to solve this?

import { projectStorage } from "@/firebase/config";
import { ref, watchEffect } from "vue";
import { ref as storageRef, uploadBytes } from "firebase/storage";

const useStorage = (file: File) => {
  watchEffect(() => {
    // references
    const storageReference = storageRef(projectStorage, "images/"   file.name);
    // upload file
    const uploadTask = uploadBytes(storageReference, file);
    // upload progress
    uploadTask.on("state_changed", (snapshot: any) => {
      console.log(snapshot);
    });
  });
};
export default useStorage;

CodePudding user response:

You must use uploadBytesResumable() instead of uploadBytes() if you need to monitor upload progress.

uploadBytes() return a Promise containing an UploadResult and uploads are not resumable. With uploadBytesResumable(), the upload can be paused and resumed, and exposes progress updates.

You can find more information in the documentation.

import { ref as storageRef, uploadBytesResumable } from "firebase/storage";

const storageReference = storageRef(projectStorage, "images/"   file.name);
const uploadTask = uploadBytesResumable(storageReference, file);

uploadTask.on("state_changed", (snapshot: any) => {
  console.log(snapshot);
});
  • Related