How to wait for one api call to complete before making another api call without using `await` in vue pinia store

46 views Asked by At

We can use await but seniors suggested me that we can do this with vue's reactivity, can some one help?

  • I am working on project in group where my senior suggested that we can use vue's reactivity to handle file upload and make final post request, however it's confusing to me what they are suggesting, below is my implementation, can some one suggest is there any better way of doing this?

App.vue

const isLoading = ref(0)

function Requester(url, method, data = null, callback = null) {
  // TODO: Remove primitive request counting technique and use reactive pattern
  isLoading.value++
  axios(url, { method: method, data: data })
    .then((response) => {
      if (callback) callback(response)
    })
    .catch((reason) => {
      alert(reason)
    })
    .finally(() => {
      isLoading.value--
    })
}

store.js

export const documentLibraryStore = defineStore('documentLibrary', () => {
  const useDocStore = doctore()
  const useGeneratedDocStore = generatedDocStore()
  const document = useGeneratedDocStore.newDocument
  const files = ref([])

  function isUploadDoneForAllFiles(uploadCount, extraFileCount) {
    return document.files.length - uploadCount == extraFileCount
  }

  function uploadPdfs() {
    let uploadCount = 0
    let extraFileCount = 0
    document.files.forEach((doc) => {
      if (!doc.id) { // id is undefind for non uploaded file
        add(doc.fileData, (value) => {
          uploadCount++
          doc.id = value.id
          // Here I am checking if files are uploaded or not
          if (isUploadDoneForAllFiles(uploadCount, extraFileCount)) {
            publish(document)
          }
        })
      } else {
        extraFileCount++
        if (extraFileCount == document.files.length) publish(document)
      }
    })
  }

  function formatPublishPayload() {
    document.files = document.files.map((file) => {
      return {
        id: file.id,
        fileId: file.fileId
      }
    })
  }
  // This should only called once we have id's for files uploaded
  function publish(documentset) {
    formatPublishPayload()
    if (document) {
      request('URL_TO_UPLOAD_DOCUMENT', 'POST', documentset, (response) => {
        useDocStore.appendDocumentSets(response.data)
        useGeneratedDocStore.clearNewDocumentSet()
      })
    }
  }

  function add(uploadFile, setID) {
    if (uploadFile) {
      const formData = new FormData()
      formData.append('file', uploadFile)
      request('URL_TO_UPLOAD_FILE', 'POST', formData, (value) => {
        files.value.push(value.data[0])
        // this is call back I am using to set id received from backend to set for uploaded files
        setID(value.data[0]) 
      })
    }
  }

  function publishDocumentSet() {
    uploadPdfs()
  }
  return { files, add, publishDocumentSet }
})
0

There are 0 answers