What is the best way to manage asynchronous functions when using Axios in Vue.js?

When I refactor code, I like to split it into three separate files for better organization.

In Users.vue, I have a method called getUsers that looks like this:

getUsers() {
      this.isLoading = true
      this.$store
        .dispatch('auth/getValidToken')
        .then((data) => {
          this.$store
            .dispatch('user/fetchUsers', data.jwt)
            .then((response) => {
              console.log('DATA RESPONSE 2', response)
              this.items = response
              this.isLoading = false
            })
            .catch((error) => {
              console.log(error)
            })
        })
        .catch((error) => {
          this.$router.push('/pages/login')
          console.log(error)
        })
    },

In user.js file, I have an action defined as follows:

fetchUsers(context, jwt) {
    return UserService.getUsers(jwt)
  },

Lastly, in UserServices.js file, I have a function to call the API:

async getUsers(jwt) {
    apiUsers.defaults.headers.common['jwt'] = jwt
    await apiUsers.get('/users').then((response) => {
      console.log('DATA RESPONSE 1', response.data)
      let data = response
      return data
    })
  },

I added console log messages to track the API response. DATA RESPONSE 1 shows me the expected object with users data, but unfortunately, DATA RESPONSE 2 displays 'undefined'.

Being a beginner in VueJS, any help or guidance would be greatly appreciated.

Answer №1

To ensure proper functionality, make sure to return the Promise from getUsers().

Consider this structure:

async getUsers(jwt) {
    apiUsers.defaults.headers.common['jwt'] = jwt
    return await apiUsers.get('/users').then((response) => {
      console.log('DATA RESPONSE 1', response.data)
      let data = response
      return data
    })
},

It is important to optimize your use of async and await. In the provided example, there is no need to await the response within getUsers() - you can simply return it. Utilize async/await appropriately in the context of Users.vue.

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

List of coordinates extracted from PolylineMeasure plugin in the React Leaflet library

I have 3 different scripts: 1. PolylineMeasure.jsx import { MapControl, withLeaflet } from "react-leaflet"; import * as L from "leaflet"; class PolylineMeasure extends MapControl { createLeafletElement() { return L.control.poly ...

Encountering a JavaScript toJSON custom method causing a StackOverflow error

Unique Scenario Upon discovering this answer, a new idea struck me - creating an object from a JSON literal. This led me to believe I could do the opposite using the handy JSON method: JSON.stringify(myObject). Curious, I proceeded as follows: function ...

Verify the identity of my Angular application to enable collaboration on a GitHub repository

In my current project, I am utilizing a specific function to retrieve the list of collaborators for a particular repository. Here is the code snippet: var getCol = function(username, reponame) { var repo; var repoUrl = "https://api.gith ...

Struggling to link an external JavaScript file to your HTML document?

While attempting to run a firebase app locally, I encountered an error in the chrome console: GET http://localhost:5000/behaviors/signup.js net::ERR_ABORTED 404 (Not Found) Do I need to set firebase.json source and destination under rewrites or add a rout ...

Shade the entire td column in different colors depending on the characteristics of th

I am working with a table and here is the code for it: <table> <thead> <tr> <th style="width: 40%; text-align: center; vertical-align: center;">Nr.<br> crt.</th> <th style="font-weight: bold; wi ...

Creating a dynamic nested list in HTML using JavaScript with data retrieved from a JSON source

I'm trying to generate a dynamic nested ul\li list from a JSON array. IMPORTANT! While I can use jQuery for this transformation, it's in a node.js environment where DOM access is restricted and I must work with a string. The depth of the a ...

Changing the entire content of a webpage from the server using AJAX

I am looking to update the entire page content with the click of a button, transitioning from Words.html to SelectNumber.html This snippet is from Words.html <html> <head> <meta charset="UTF-8"> <title>Number Game< ...

Access the style of the first script tag using document.getElementsByTagName('script')[0].style or simply refer to the style of the document body with document.body.style

Many individuals opt for: document.getElementsByTagName('script')[0].style While others prefer: document.body.style. Are there any notable differences between the two methods? EDIT: Here's an example using the first option: ...

SWR NextJS error remains unhandled despite being thrown

I'm struggling to manage errors thrown in my SWR fetcher. Currently, whenever an error is thrown, my app stops working and I see an "Unhandled Runtime Error". What I've been doing is throwing the error inside the fetcher function. Here's th ...

Show JSON array items

My php file (history.php) generates a JSON object $i=1; $q=mysql_query("select * from participants where phone='".mysql_real_escape_string($_GET['phone'])."' limit 10"); while($rs=mysql_fetch_array($q)){ $response[$i] = $rs[&ap ...

I am having difficulty accessing specific data in JSON using Searchkit's RefinementListFilter

Utilizing searchkit for a website, I am encountering issues accessing previously converted data in json format. The structure of my json directory is as follows: (...) hits: 0: _index: content _type: content _source: ...

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 ...

Tips for preventing recursion when utilizing scrollIntoView() in a scroll event handler

My goal is to break down my website into screen-sized sections that automatically scroll to the next section when a user begins scrolling. I attempted to accomplish this by using the following code: $(window).scroll(function() { getElementToScroll().s ...

Issue with retrieving relative time using Moment.js - fromNow()

I want to utilize moment.js to display relative time fromNow(), but I am encountering an issue where the values are being rounded and showing higher durations instead of exact completion times. For example, moment().subtract('s',110).fromNow() / ...

Error 405 (Unauthorized) encountered with the stack of technologies including Vue.js, Nginx, Axios, SQLite, and Express

I successfully developed an application that handles user login and registration to a SQLite database on `localhost`, but I am encountering issues when trying to deploy it. The deployment results in an error message saying `405 (Not Allowed)` with the acco ...

Clicking on links will open them in a separate tab, ensuring that only the new tab

Is there a way to open a new tab or popup window, and have it update the existing tab or window whenever the original source link is clicked again? The current behavior of continuously opening new tabs isn't what I was hoping for. ...

Achieving VueJS reactivity by initializing a variable within the mounted function

I am facing an issue with a dynamic component that builds multiple select elements. Here is the template code: <template> <div> <b-field v-for="(key,index) in allSelects" :key="index" :label=" ...

What are the ways to change a PDF file or web address into a DOCX document using NodeJS?

I've been doing some research on converting URLs to DOCx or PDF to DOCx in NodeJS, but I haven't found a proper solution yet. I tried reaching out to PhantomJS, but it only converts URLs to PDF. Do you have any idea if PhantomJS can convert to D ...

Use JavaScript to add a div element to the page ten times every time the button is clicked

Here is the code I have written: $(document).ready(function () { $('<button class="btn more">View More</button>') .appendTo(".listing-item-container") .click(function() { $(this).closest(". ...

What is the best way to include a &nbsp; in a map function using JavaScript?

A challenge I encountered while working in React is as follows: <Grid item> { rolePriorities.map((rp, index) => ( <Chip key={index} label={rp} color="primary" sx={{ color: "whitesmoke" }} /> ...