简体   繁体   中英

How to properly use the object array from axios get function to outside function

I'm trying to get a data from axios get request to be used for q-table rows and I was able to get it and use it on v-for. However I was not able to use it outside the axios function as it shows as empty array.

Here's my full code

<template>
  <div class="q-pa-md">
    <q-table
      title="Treats"
      :rows="rows" <<-- Was not able to use the data from axios since it returns an empty array -->>
      :columns="columns"
      row-key="name"
    />
    <div v-for="name in fetchUsers.data" :key="name.name">
    {{name.email}} <<-- Was able to use the data from axios -->
    </div>
  </div>
</template>

<script setup>
import { getCurrentInstance, ref } from 'vue'
const { $api } = getCurrentInstance().appContext.config.globalProperties // axios

const fetchUsers = ref([])

const users = () => {
  const usersB = []
  $api.get('users')
    .then(response => {
      fetchUsers.value = response.data
      const usersA = fetchUsers.value.data.map(obj => {
        return {
          name: obj.name,
          email: obj.email
        }
      })
      usersB.push(...usersA) // If I console.log(usersB) here, it shows a non empty array
    })
    .catch(error => {
      console.log(error)
    })
  console.log(usersB)
  return usersB
}

console.log(users()) // Shows zero array but shows there's a value like on below example
// []
// 0: {name: 'Eric', email: 'eric@eric.com'}
// 1: {name: 'John Lennon', email: 'john@beatles.com'}
// 2: {name: 'Eric', email: 'eric1@eric.com'}
// 3: {name: '', email: ''}

const columns = [
  {
    name: 'name',
    required: true,
    label: 'Dessert (100g serving)',
    align: 'left',
    field: row => row.name,
    format: val => `${val}`,
    sortable: true
  }
]

const rows = [ // => Main goal value after the object from axios are converted into array
  {
    name: 'Frozen Yogurt',
    calories: 159,
    fat: 6.0,
    carbs: 24,
    protein: 4.0,
    sodium: 87,
    calcium: '14%',
    iron: '1%'
  }
]

</script>

result of calling users()

Am I missing a syntax on this? I'm trying to understand the old related posts. However, it is still not working.

Array/List length is zero but Array is not empty

Your issue stems from the (incorrect) use of a promise. The promise executes asynchronously, that is after you return an empty array


const users = () => {
  const usersB = []
  $api.get('users')
    .then(response => {
      fetchUsers.value = response.data
      const usersA = fetchUsers.value.data.map(obj => {
        return {
          name: obj.name,
          email: obj.email
        }
      })
      usersB.push(...usersA) // <=== this executes later, when request is resolved
    })
    .catch(error => {
      console.log(error)
    })
  console.log(usersB)
  return usersB // <=== this executes first 
}

There are a few ways of handling properly. Here's an example with ref

// define the `ref`
const users = ref([])

// load users function (though it doesn't need to be in encapsulated)
const loadUsers = () => {
  $api.get('users')
    .then(response => {
      fetchUsers.value = response.data
      const usersA = fetchUsers.value.data.map(obj => {
        return {
          name: obj.name,
          email: obj.email
        }
      })
      // update ref value
      users.value = [...usersA]
    })
    .catch(error => {
      console.log(error)
    })
}

// call the function
loadUsers()

in your template you can now use users which will be reactive, so when the API loads it will update, which will trigger a change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM