Home > database >  Vue 3 using function inside setup
Vue 3 using function inside setup

Time:05-05

I am doing a simple app and I am using mock-json-server to simulate http request.

I have defined a function to get the info I need :

import { ref } from 'vue'

const getScores = () => {
const scoringPass = ref([])
const error = ref(null)

const load = async () => {
  try {
    let data = await fetch('http://localhost:8000/scores', {
    method: 'get',
    headers: {
        'content-type': 'application/json'
    }})
    if (!data.ok) {
          throw Error('no data available')
    }
    scoringPass.value = await data.json()
    console.log(scoringPass.value)
  } catch (err) {
    error.value = err.message
    console.log(error.value)
  }
}
return { scoringPass, error, load }
}

export default getScores

And I call it in the setup function of my component :

  <script lang="ts">
    import { defineComponent } from 'vue'
    import Pass from '@/components/Pass.vue'
    import getScores from '../composables/getScores.js'

    export default defineComponent({
    setup() {
      const numeroDossier = '25020230955000004'
      const { scoringPass, error, load } = getScores()

      load()
      return { numeroDossier, scoringPass, error }
    },
    components: {
      Pass,
     },
    })
    </script>

In the console.log(scoringPass.value) in the function, I can see the data. but the load() function in the setup part does not work and I can't figure out why. It is called though, but I can't get the data.

When I do console.log(load()), I get :

Promise {<pending>}
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: undefined

Any help appreciated. Cheers.

CodePudding user response:

load() is async, so its return value is a Promise. You have to await the call to get the underlying data. However, load() doesn't actually return anything, so you still wouldn't see any data. If you want load() to provide the initial value of scoringPass, load() should return that:

const load = async () => {
  try {
    ⋮
    return scoringPass.value
  } catch (err) {
    ⋮
    return null
  }
}

To get the result of load(), you can wrap the call in an async function to await the call; or chain a .then() callback:

export default defineComponent({
  setup() {
    ⋮
    const logLoadResults = async () => console.log(await load())
    logLoadResults()

    // or
    load().then(results => console.log(results))
  }
})

Don't mark setup() as async because that would make your component an async component, requiring a <Suspense> in a parent component to render it.

  • Related