Utilizing Vue JS - Creating Async Await function to retrieve data resulting in undefined output

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

Answer №1

Here are some solutions to the errors in your code:

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

Answer №2

If you're unsure about how promises function, update your code to:

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

Then, when implementing it with async/await, consider using try catch blocks:

async fetchData () {
   try {
      const {information} = await this.retrieveUserData(456)

      this.userData.info = information
      this.$nextTick(() => this.completed = true)
   } catch (error) {
      // handle the error accordingly
   }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for dynamically updating a variable's state within a render function?

I'm currently working on a project for my class where we are tasked with creating a website using React. Unfortunately, neither myself nor my group members have been able to figure out how to render a function in a variable state and make it dynamic. ...

The constant reloading of the page is hindering the crucial display of the data

After successfully getting something to work, I noticed that the data disappears when the page refreshes. How can I prevent this from happening? <html> <head> <meta charset="utf-8"> <title> IT Services </ti ...

What is the best way to determine when a function has completed its execution in jQuery?

Below is the code snippet provided: function loadLog() { var oldscrollHeight = $("#chatbox")[0].scrollHeight - 20; //Scroll height before the request $.ajax({ url: "log.html", cache: false, success: function(html) { ...

Utilizing JavaScript or jQuery to adjust the cursor pointer value based on user input

Issue: Need help with live updating of input value to range input pointer [Check out my CodePen for reference][1] Adjust upper range input pointer based on lower range input pointer ][2] I am currently working on a range-to-range calculator for a book ...

How can I remove markers from google maps?

I have been working on a program that dynamically loads JSON data onto a map as markers when the user pans and zooms. However, I am facing an issue where I need to clear the existing markers each time the user interacts with the map in order to load new on ...

Utilizing AngularJS for manipulating a multidimensional array with interdependent select boxes

I have a unique collection of product names along with their respective versions stored in a multidimensional array. My goal is to design an interactive interface that allows users to first select a product from a drop-down menu and then choose the version ...

Attempting to conceal the API, however, the backend is throwing an error

view the error image I am currently in the process of developing an NFT search application that is capable of locating the NFTs associated with a specific wallet address. However, I am faced with the challenge of using Alchemy without exposing the API key ...

Guide to utilizing a ref in multiple components within Vuejs

I'm currently working on a project that involves two components (Title and Input components) with the same title reference. The requirement is for changes made to one component to reflect in the other as well. I attempted to implement suggestions from ...

Show whether the day is even or odd with the JavaScript getDay object

I'm currently working on a task where I need to show the text "Even Day" if the day of the month is 2, 4, 6..., and "Odd Day" for days such as 1, 3, 5, and so on. I attempted to achieve this by setting up an array linked to the getDay object, but unfo ...

Limit the width and height of MUI Popper with a maximum setting

After experimenting with the popper API from MUI, I discovered that it extends beyond my main div. Does anyone have suggestions on how to prevent this overflow? I am looking to increase the height of the popper. Please refer to the code snippet below: con ...

What is the correct way to outline the parameters for deactivating functions?

Request for Assistance! I am facing a challenge with multiple blocks in my WordPress website. Each block contains a checkbox, two select options, and an element that needs to be toggled based on the selected options in the dropdowns. The functionality to ...

Authentication Error: Middleware did not detect an authorization token for JWT login

I recently attempted to implement login and registration functionality in my Node.js application using JWT tokens by following a tutorial. However, I am encountering difficulties with the login process and redirecting users to the 'logged in' adm ...

LazyTreeGrid from Dojo encounters issues with paginating children while using QueryReadStore

Currently, I am experimenting with the LazyTreeGrid implementation in Dojo and have encountered an issue. When LazyTreeGrid is paired with LazyTreeGridStoreModel and QueryReadStore for pagination of children nodes, errors sometimes arise. I attempted to l ...

What is the process for cancelling a jQuery 3.0 AJAX request?

What is the best way to cancel an AJAX request in jQuery 3.0? this.request = $.ajax(); The newer version of jQuery does not support the abort method in promises. if(this.request && this.request.state() == 'pending') { this.request.abort(); & ...

Canvas - Drawing restricted to new tiles when hovered over, not the entire canvas

Imagine having a canvas divided into a 15x10 32-pixel checkerboard grid. This setup looks like: var canvas = document.getElementById('canvas'); var context = canvas.getContext('2d'); var tileSize = 32; var xCoord var yCoord ...

Vuetify enabling dynamic calculations in real-time

I'm currently working on a Vuetify-based dynamic calculator project. Below is the code snippet I am using: <v-row class="mt-8 align-self-center"> <v-col cols="2"> <v-text-field :value="weight" ...

inputting a pair of parameters into a function

While creating an action for react-redux, I encountered a problem when trying to pass two variables into the function - dispatch and hosts. Strangely, the variable host is being logged as a function instead of its actual value. This is my code: export fu ...

React-easy-crop simply provides a blob url as a result

Currently, I am utilizing the react-easy-crop package to enable users to make adjustments to their profile pictures post uploading. However, I have encountered an issue where the cropped image is returned in the form of a blob URL such as blob:http://local ...

Track changes and save only the updated elements in an array

Currently, I am utilizing Angular for the front end, C# for the backend, and an Oracle database for a project with a company. Within the grids provided to me, there are more than 120 records that users can edit individually. My dilemma lies in identifyin ...

Is there a way to prevent Express from automatically adding a slash to a route?

Despite my extensive search for a solution, none of them have proven effective. Perhaps you could provide some assistance. I'm currently working on a Node.JS and Express-based plugin webserver. The main code for the webserver is as follows: This sec ...