Reputation: 99
I am successfully managing to upload files to the firebase storage.
However, when I include the .on function with statechanged, the console throws the following error:
Error: Reference.push failed: first argument contains undefined in property 'testimonials.clientImg'
I am trying to retreive the image URL and place it in a variable.
My code is shown below, please can anyone assist?
let itemsRef = firebase.database().ref('testimonials');
let imgFile = this.state.currentImg;
let imageRef;
let imgURL;
if (imgFile){
imageRef = firebase.storage().ref("testimonialPics/"+imgFile.name).put(imgFile);
imageRef.on('state_changed', (snapshot)=>{
console.log(snapshot);
})
let clientObj = {
name: this.state.currentName,
feedback: this.state.currentComments,
approved: false,
clientImg: imgURL
}
itemsRef.push(clientObj);
console.log(clientObj);
this.setState({
currentName: "",
currentComments: "",
currentImg: null
})
Upvotes: 0
Views: 121
Reputation: 600006
You're not giving imgURL
a value anywhere in this code, which would match with the fact that it's undefined
when you call itemsRef.push(clientObj)
and (as the error message says, you can't write an undefined value to the database.
It looks like you're trying to write the download URL to the database. I'd following the example in the documentation closely for that. But based on your current code, it should be something like:
let itemsRef = firebase.database().ref('testimonials');
let imgFile = this.state.currentImg;
let imageRef;
let imgURL;
if (imgFile){
let ref = firebase.storage().ref("testimonialPics/"+imgFile.name);
let task = ref.put(imgFile);
task.then(() => {
// this runs when the upload has completed
ref.getDownloadURL().then(function(downloadURL) {
// this runs when the download URL has been determined
let clientObj = {
name: this.state.currentName,
feedback: this.state.currentComments,
approved: false,
clientImg: downloadURL
}
itemsRef.push(clientObj);
this.setState({
currentName: "",
currentComments: "",
currentImg: null
})
})
})
Upvotes: 1
Reputation: 304
https://firebase.google.com/docs/storage/web/download-files#download_data_via_url Try this out. I think you are listening to the wrong listener.
Upvotes: 1