Reputation: 139
I just want to upload an image then get is URL to save to firestore because i want to save the url of that image to an object. I just want the await to wait for the upload to be finished and then to get the url.
Problem is when i try to get the url it says it doesnt exist but when i go to firebase is there.
const fileData = await fileUpload(imageHome, values.newHomeTeamName);
const url = await storage.ref(fileData).getDownloadURL();
console.log(url);
const fileUpload = async (image: File, newHomeTeamName: string) => {
const fileName = formatFileName(image.name, newHomeTeamName);
const uploadTask = storage.ref(fileName).put(image);
await uploadTask.on(
'state_changed',
snapsphot => {},
error => {
console.log(error);
}
);
return fileName;
};
Upvotes: 0
Views: 588
Reputation: 598688
Your fileUpload
function looks a bit unusual to me. You're using await
on the on()
call, but that doesn't return a promise. What you should do instead is wait
on the task itself. So something like:
const fileUpload = async (image: File, newHomeTeamName: string) => {
const fileName = formatFileName(image.name, newHomeTeamName);
const uploadTask = storage.ref(fileName).put(image);
await uploadTask;
return fileName;
}
Or a bit simpler:
const fileUpload = async (image: File, newHomeTeamName: string) => {
const fileName = formatFileName(image.name, newHomeTeamName);
await storage.ref(fileName).put(image);
return fileName;
}
If you want to handle the error, you can catch
it in there too. But since all you do is log it, I'd recommend letting it escape and leave it to the runtime to log it.
Upvotes: 1
Reputation: 1283
This is what i did for my app and the url does get stored in the firestore
//imports
import { storage, db } from './firebase'
import firebase from 'firebase'
//states or hooks
const [caption, setCaption] = useState('')
const [image, setImage] = useState(null)
const [progress, setProgress] = useState(0)
const handleUpload=()=>{
const uploadTask = storage.ref(`images/${image.name}`).put(image);
uploadTask.on(
'state_changed',
(snapshot)=>{
const progress = Math.round(
(snapshot.bytesTransferred / snapshot.totalBytes) *100
);
setProgress(progress)
},
(error)=>{
console.log(error);
alert(error.message);
},
()=>{
storage
.ref('images')
.child(image.name)
.getDownloadURL()
.then(url =>{
db.collection('posts').add({
timestamp: firebase.firestore.FieldValue.serverTimestamp(),
caption: caption,
imageUrl: url,
username: uploadname
});
setImage(null);
setProgress(0);
setCaption("");
})
}
)
}
The handleUpload
trigress off when the upload button is clicked
Upvotes: 0