Please can someone help me. I think the way I am handling the promise is wrong and really need someone to help me.
I am letting the user upload a picture . When the user presses submit the image is uploaded to firebase-storage. However I don't think I am handling the wait period to upload the image and setting the data to firebase-database. What I mean is when I press submit I get the error FireBase Function DocumentReference.set() called with invalid data
Because it is setting the image to undefined
However if I wait a couple of seconds I get the console.log("File available at" + downloadUrl)
which means the image was uploaded.
Basically I just need to add a waiting period to my code between when the image is uploaded and when to send the data to the firebase-database
This is my code any help will be much appreciated !!!!!
const uploadImage = async (uri, imageName) => {
const response = await fetch(uri)
const blob = await response.blob()
var ref = firebase.storage().ref().child(`images/${imageName}`)
ref.put(blob)
.then(()=>{
// Upload completed successfully, now we can get the download URL
var storageRef = firebase.storage().ref('images/' + imageName)
storageRef.getDownloadURL().then((downloadUrl)=>{
console.log(`File available at ${downloadUrl}`)
setDownload(JSON.stringify(downloadUrl))
})
})
.catch(error => {
setRefreshing(false) // false isRefreshing flag for disable pull to refresh
Alert.alert("An error occured", "Please try again later")
});
}
const handleSubmit = useCallback(() => {
if (postImage !== undefined) {
const fileExtention = postImage[0].split('.').pop()
const fileName = `${uniqid}.${fileExtention}`
uploadImage(postImage, fileName)
firebase.firestore()
.collection('Posts')
.doc(uniqid)
.set({
id: currentUser,
name: postName[0],
image: downloadImage,
})
}
})
Thank you in advance for all your help!!!!!
To use await inside useCallback
you can try to wrap the code inside it in a self invoking function like this:
const handleSubmit = useCallback(() => {
(async () =>{ if (postImage !== undefined) {
const fileExtention = postImage[0].split('.').pop()
const fileName = `${uniqid}.${fileExtention}`
uploadImage(postImage, fileName)
await firebase.firestore()
.collection('Posts')
.doc(uniqid)
.set({
id: currentUser,
name: postName[0],
image: downloadImage,
})
}
})()
})