Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

342
Visualizações
Vue JS - Helper Async Await function to fetch data returning undefined

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)
    });
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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;
  }
}
about 4 years ago · Juan Pablo Isaza Relatório

0

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
   }
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda