[Vuejs]-Vue JS โ€“ Helper Async Await function to fetch data returning undefined

2๐Ÿ‘

โœ…

you got a few errors in your code here are the solutions:

component.vue

import { currentDateTime , fetchUserData } from '@/helpers/util.js';
export default {
    data () {
        return {
            userData: null,
            loaded: false
        }
    },
    methods : {
        currentDateTime , fetchUserData ,
        async setData () {
            const { data } = await fetchUserData(123);
            this.loaded = true
            this.userData.name = data.name
        }
    },
    created() {
        this.setData()
    }
}

util.js

import axios from 'axios';

export async function fetchUserData(id) {
  try {
    const response = await axios.get('/data-table/' + id);
    return response;
  } catch (e) {
    throw e;
  }
}
๐Ÿ‘คMartinez

1๐Ÿ‘

Some confusion on how promises work, change your code to:

export function fetchUserData( id ) {
    return axios.get('/data-table/' + id )
}

Then when you use it like, switching to try catch as your using async/await

async setData () {
   try {
      const {data} = await this.fetchUserData(123)

      this.userData.name = data.name
      this.$nextTick(() => this.loaded = true)
   } catch (err) {
      // do something with err
   }
}

Leave a comment