I am running into a problem. I want to create a simple image upload input and the images should be stored in a Firebase Storage. I think I have mixed up some v8 and v9 code, but I can't also find a right answer.
When I trigger the upload, I get this error message:
TypeError: _firebase_firebase__WEBPACK_IMPORTED_MODULE_1__.storage.ref is not a function
61 |
62 | const uploadFiles = () => {
63 | //
> 64 | const uploadTask = storage.ref(`images/${img.name}`).put(img);
| ^ 65 | uploadTask.on(
66 | "state_changed",
67 | (snapshot) => {
This is my code I am running:
import React, { useState } from "react";
import { storage } from "../../firebase/firebase";
import { ActionBtn, Topbar, SubjectHead, CardList } from "../../components/styles";
const CreateImg = () => {
const [img, setImg] = useState(null);
const [progress, setProgress] = useState(0);
const formHandler = (e) => {
e.preventDefault();
const file = e.target.files[0];
setImg(file);
};
const uploadFiles = () => {
const uploadTask = storage.ref(`images/${img.name}`).put(img);
uploadTask.on(
"state_changed",
(snapshot) => {
const prog = Math.round(
(snapshot.bytesTransferred / snapshot.totalBytes) * 100
);
setProgress(prog);
},
(error) => console.log(error),
() => {
storage
.ref("images")
.child(img.name)
.getDownloadURL()
.then((url) => {
console.log(url);
});
}
);
};
return (
<div>
<Topbar>
<SubjectHead>Create New CV</SubjectHead>
<ActionBtn onClick={createCv}>Create CV</ActionBtn>
</Topbar>
<CardList type="form">
<div>
<div>
<input
type="file"
accept=".jpg,.png,.jpeg"
onChange={formHandler}
/>
<button type="button" onClick={uploadFiles}>
Upload
</button>
<h4>{progress}%</h4>
</div>
</CardList>
</div>
);
};
export default CreateImg;
Here is my config file:
import { initializeApp } from "firebase/app";
import { getStorage } from "firebase/storage";
const firebaseConfig = {
apiKey: "XXX",
authDomain: "XXX",
projectId: "XXX",
storageBucket: "XXX",
messagingSenderId: "XXX",
appId: "XXX",
};
const app = initializeApp(firebaseConfig);
const storage = getStorage(app);
export { storage };
I would be super happy if someone could help me with my issue. Thanks in advance.
CodePudding user response:
Your imports:
import { getStorage, ref } from "firebase/storage";
Then create the ref:
const storage = getStorage();
const storageRef = ref(storage, `images/${img.name}`); //note that ref is not a function on storage -- it's a separately imported function
Set the metadata:
const metadata = {
contentType: 'image/jpeg'
};
Start and monitor the upload:
const uploadTask = uploadBytesResumable(storageRef, file, metadata);
uploadTask.on('state_changed',
(snapshot) => {
//etc
More documentation: https://firebase.google.com/docs/storage/web/upload-files#upload_files