I am building a form where the user needs to input information to create a city document. The user also needs to upload multiple photos of the city. When submitting the form, a new city document is created in firestore, then each photo is uploaded to the associated firebase storage, and finally a new field called photosURLs
with all the photos URLs is added to the city document.
Here is my code:
async function addDocument() {
const docRef = await addDoc(collection(db, "cities"), {
name: "Tokyo",
country: "Japan"
});
return docRef
}
async function UploadMultiplePhotos(docRef) {
var photos = []
for (var i = 0; i < files.value.length; i++) { // files.values contains all the files objects
const file = files.value[i];
refStorageFunction(
storage,
"cities/" +
docRef.id +
"/" +
file.name
);
uploadBytes(storageRef, file).then((snapshot) => {
getDownloadURL(snapshot.ref).then((downloadURL) => {
photos.push(downloadURL)
});
});
}
return Promise.resolve(photos)
}
async function updateDocument(docRef, photos) {
await updateDoc(docRef, { photosURLs: photos });
}
function createCity() {
addDocument().then((docRef) => {
UploadMultiplePhotos(docRef).then((photos) => {
updateDocument(docRef, photos).then(() => {
router.push($CITY_PATH)
})
})
})
}
My issue is that the resulting photosURLs
field in the city document is empty. It seems my function UploadMultiplePhotos
does not wait for the photos
array to be completely populated.