Home > Net >  Passing an axios response to the template in Vue 3 & Composition API
Passing an axios response to the template in Vue 3 & Composition API

Time:11-14

<template>
  <div >
    <h1>BPMN Lint Analyzer</h1>
    <!-- Get File from DropZone -->
    <DropZone @drop.prevent="drop" @change="selectedFile"/>
    <span >File:{{dropzoneFile.name}}</span>
    <button @click="sendFile" >Upload File</button>
    <!-- Display Response Data (Not Working)-->
    <div v-if="showResponseData">
      <p>Testing: {{responseData}}</p>
    </div>
  </div>
</template>

<script>
import DropZone from '@/components/DropZone.vue'
import {ref} from "vue"
import axios from 'axios'

export default {
  name: 'HomeView',
  components: {
    DropZone
  },
  setup(){
    let dropzoneFile = ref("")

    //Define Response variable and visibility toggle
    var responseData=''
    // var showResponseData = false

    //Methods
    const drop = (e) => {
      dropzoneFile.value = e.dataTransfer.files[0]
    }
    const selectedFile = () => {
      dropzoneFile.value = document.querySelector('.dropzoneFile').files[0]
    }

    //API Call
    const sendFile = () => {
      
      let formData = new FormData()
      formData.append('file', dropzoneFile.value)


      axios.post('http://localhost:3000/fileupload', formData,{
        headers: {
          'Content-Type':'multipart/form-data'
        }
      }).catch(error => {
        console.log(error)
      }).then(response => {
        responseData = response.data
        console.log(responseData);
      })
      // showResponseData=true
    }
    return{dropzoneFile, drop, selectedFile, sendFile}
  }
}
</script>

I'm trying to pass the response from sendFile, which is stored in responseData back to the template to display it in a div to begin with. I'm not sure if a lifecycle hook is needed.

Current output: enter image description here

I played around with toggles, I tried to convert everything to options API. Tried adding logs but I'm still struggling to understand what I'm looking for.

Unfortunately I am stuck with the Composition API in this case even if the application itself is very simple. I'm struggling to learn much from the Docs so I'm hoping to find a solution here. Thank you!

CodePudding user response:

You need to make responseData reactive, so try to import ref or reactive from vue:

import {ref} from 'vue'

then create your variable as a reactive:

const responseData = ref(null)

set data to your variable:

responseData.value = response.data

in template check data:

<div v-if="responseData">
  <p>Testing: {{responseData}}</p>
</div>

finally return it from setup function (if you want to use it in template):

return{dropzoneFile, drop, selectedFile, sendFile, responseData}
  • Related