While working in vuejs, I have a helper file containing custom functions that are used throughout the project.
Recently, I was refactoring some async await promises, but ran into an issue that I can't seem to resolve.
I want to call the fetchUserData(123) function and receive the data back in the method. However, even though the request is successful with valid results, the userData constant remains undefined.
What could be causing this issue?
Within component.vue, an error message is displayed: 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()
}
}
Another section in component.vue shows the value as undefined:
async setData () {
const userData = await fetchUserData(123)
console.log(userData )
}
In the util.js file:
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)
});
}