Home > OS >  Vue JS - Helper Async Await function to fetch data returning undefined
Vue JS - Helper Async Await function to fetch data returning undefined

Time:05-11

In vuejs I'm using a helper file with some custom functions that I ll use everywhere in the project.

I was refactoring some async await promises, but I cant seem to solve it.

I wish to call the fetchUserData(123), for example, and get the data back to the method. Although the request is made and have valid results, the userData const is undefined.

What I'm doing wrong ?

component.vue : this one prints out, Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'then')

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

            userData.then(response => {
                console.log(response) // prints undefined
                this.loaded = true
                this.userData.name = response.data.name
                // other logic ...
            })
        }
    },
    created() {
        this.setData()
    }
}

component.vue : this one prints out, undefined

async setData () {
            const userData = await fetchUserData(123)
console.log(userData )

        }

util.js

import axios from 'axios';


export function capitalizeFirstLetter(str) {
    return str.charAt(0).toUpperCase()   str.slice(1);
}
export function zeroPad(num, places) {
    return String(num).padStart(places, '0')
}
export function currentDateTime () {
    const current = new Date()
    const date = zeroPad ( current.getDate() , 2 )   '/'   zeroPad( ( current.getMonth()   1 ) , 2 )   '/'   current.getFullYear()
    const time = zeroPad ( current.getHours() , 2 )   ":"   zeroPad ( current.getMinutes() , 2 )   ":"   zeroPad ( current.getSeconds() , 2 )
    const dateTime = date  ' '  time
    return dateTime
}
export async function fetchUserData( id ) {
    await axios.get('/data-table/'   id ).then(response=> {
console.log(response) // works
        return response
    }).catch(error => {
        console.log(error)
    });
}

CodePudding user response:

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;
  }
}

CodePudding user response:

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
   }
}
  • Related