My experience with building async functions is minimal, and the documentation has left me feeling even more confused.
I am using vue.js as my framework and making calls to firebase in my methods.
Aim
The issue arises when deleting a document in firebase; nested documents are not deleted automatically. To address this, I had to create a custom delete function using recursive functions within a mixin. Although the mixin now works, there is a problem where the reload emit event fires before the delete function completes, leaving a ghost element in the DOM.
I need $emit('reload')
to wait until all firebase calls in deleteProject()
have finished.
Code Snippet
<script>
import { deleteProject } from '../../../mixins/deleteData'
export default {
mixins: [deleteProject],
props: ['yearId', 'projectId', 'project'],
name: 'deleteProjectModal',
data: () => ({
dialog: false
}),
methods: {
del () {
// call deleteYear method from mixin
this.deleteProject(this.yearId, this.projectId)
// emit reload signal for database relaod
this.$emit('reload')
// close modal
this.dialog = false
}
}
}
</script>
import firebase from '@/firebase/init'
export const deleteProject = {
methods: {
deleteProject (yearId, projectId) {
// delete project, all documents in the images subcollection of the project, and all stored images
firebase.firestore().collection('years').doc(yearId).collection('projects').doc(projectId).get()
.then((doc) => {
// delete thumbnail
firebase.storage().ref(doc.data().thumbFullPath).delete()
// delete project document
firebase.firestore().collection('years').doc(yearId).collection('projects').doc(projectId).delete()
firebase.firestore().collection('years').doc(yearId).collection('projects').doc(projectId).collection('images').get()
.then((querySnapshot) => {
querySnapshot.forEach((doc) => {
// delete gallery image
this.imagePaths.append(doc.data().fullPath)
// delete reference document for gallery image
doc.ref.delete()
})
})
})
}
}
}
Attempts Made
I believe the solution involves converting deleteProject()
into an async function and calling
deleteProject().then($emit('reload'))
. However, I haven't been able to successfully implement this.
Edit
Upon request, here is the function triggered by reload
:
import firebase from '@/firebase/init'
export const loadGallery = {
data: () => ({
years: []
}),
methods: {
loadProjects () {
var years = []
var temp = []
firebase.firestore().collection('years').orderBy('year', 'desc').onSnapshot((querySnapshot) => {
querySnapshot.forEach((year) => {
firebase.firestore().collection('years').doc(year.id).collection('projects').get().then((querySnapshot) => {
querySnapshot.forEach((project) => {
var objectMicro = { title: project.data().title, thumbUrl: project.data().thumbUrl, route: project.data().route, id: project.id }
temp.push(objectMicro)
})
}).then(() => {
var objectMacro = { year: year.data().year, id: year.id, projects: temp }
years.push(objectMacro)
temp = []
})
})
})
this.years = years
}
}
}