Reputation: 11
Im new in web development . i tried to find an answer all over the internet in the past 24 hours without success and now im reaching out here
this is my err :
Uncaught TypeError: firebase__WEBPACK_IMPORTED_MODULE_3_.storage.ref is not a function
this is the firebase.js file :
import { initializeApp } from 'firebase/app';
import { getStorage } from 'firebase/storage';
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: ""
};
const app = initializeApp(firebaseConfig);
export const storage = getStorage(app);
and im importing the storage in the component like that :
import {storage} from "../../firebase";
this is the upload func :
const upload = (items) => {
items.forEach((item) => {
const fileName = new Date().getTime() + item.label + item.file.name;
const uploadTask = storage.ref(`/items/${fileName}`).put(item.file);
uploadTask.on(
"state_changed",
(snapshot) => {
const progress =
(snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log("Upload is " + progress + "% done");
},
(error) => {
console.log(error);
},
() => {
uploadTask.snapshot.ref.getDownloadURL().then((url) => {
setMovie((prev) => {
return { ...prev, [item.label]: url };
});
setUploaded((prev) => prev + 1);
});
}
);
});
};
any suggestions ?
Upvotes: 1
Views: 1914
Reputation: 26171
You are using the syntax for the legacy namespaced Firebase JS SDK (v8 and older) with the newer modular Firebase SDK (v9 and newer).
Instead of storage.ref()
, you need to be using ref(storage, path)
:
import { storage } from "../../firebase"
import { ref, uploadBytes } from "firebase/storage";
const upload = (items) => {
items.forEach((item, index) => {
const storageRef = ref(storage, `/items/${fileName}`);
const uploadTask = uploadBytes(storageRef, item.file);
uploadTask.on(
"state_changed",
(snapshot) => {
const progress =
Math.round((snapshot.bytesTransferred / snapshot.totalBytes) * 1000)/10;
console.log(`Upload #${index+1} is ${progress}% done`);
},
(error) => {
console.log(error);
},
() => {
console.log(`Upload #${index+1} is complete, fetching URL...`);
getDownloadURL(storageRef)
.then((url) => {
console.log(`Upload #${index+1} is now available at ${url}.`);
setMovie((prev) => {
return { ...prev, [item.label]: url };
});
setUploaded((prev) => prev + 1);
})
.catch((error) => {
console.log(error);
});
}
);
});
}
I encourage you to read the documentation completely and read the migration guide so that you can see which SDK version the code you are working off of was built for.
Note: You should further improve this code to handle errors better, such as set an error message visible to the user for failed uploads.
Upvotes: 2