Assigning a variable in Vue.js after making a call with axios

One of the challenges I'm facing is trying to call axios using this.request(url) within a mixin. The goal is to streamline and consolidate all axios-related functionality in a single file, but I'm running into some issues.

In my Vue file:

export default {
  name: "employees-list",
  data() {
    return {
      employees: []
    }
  },
  mounted() {
    this.employees = this.request('https://jsonplaceholder.typicode.com/posts');
  }
}

Request.js:

Vue.mixin({
  methods: {
    request: function (url) {
      axios.get(url)
        .then(response => {
        return response.data
      })
        .catch(e => {
        this.errors.push(e)
      })
    }
  }
});

The issue I'm encountering is that the employees variable appears as "undefined."

I suspect that the problem lies with asynchronous processing or the concept of async/await, but I'm still grappling with understanding it fully.

Answer №1

If you're looking to use the mixin to create a universal method for fetching data, then make sure to return the promise from the request function and handle the retrieved data in the success callback.

Check out this example below:

console.clear()

const EmployeesList = {
  name: "employees-list",
  template: `
      <ul>
        <li v-for="employee in employees">{{employee.title}}</li>
      </ul>
    `,
  data() {
    return {
      employees: []
    }
  },
  mounted() {
    // Just using posts as an example here instead of actual employees.
    this.request('https://jsonplaceholder.typicode.com/posts')
      .then(e => this.employees = e);
  }
}

Vue.mixin({
  methods: {
    request: function(url) {
      // Return the promise
      return axios.get(url)
        .then(response => {
          return response.data
        })
        .catch(e => {
          this.errors.push(e)
        })
    }
  }
});

new Vue({
  el: "#app",
  components: {
    EmployeesList
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.17.1/axios.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>

<div id="app">
  <employees-list></employees-list>
</div>

Answer №2

Give this a try:

const app = new Vue({
    el: '#app',
  data: {
    users: []
  },
  methods: {
    fetchData(url){
        return new Promise((resolve, reject) => {
        axios.get(url)
          .then(response => {
            resolve(response);
          }).catch(error => {
            // error handling
          });
      });   
    }
  },
  mounted(){
   this.fetchData('https://jsonplaceholder.typicode.com/users').then(response => {
    this.users = response;
   })
  }
})

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

Is it possible to create an async hover provider in a VSCode extension?

Currently, I'm working on a vscode extension where I need to perform a database lookup using a string that the user hovers over as a key. I have implemented a hover provider as an async function, but unfortunately, it is not displaying when I hover ov ...

Tips for obtaining an Amazon email within an Alexa SDK V2 skill

I am currently working on creating an Alexa skill and I need assistance with extracting the user's email in order to compare it with a database. Most of the resources I found online are using SDK v1, which is outdated now. Does anyone have expertise i ...

CMS that utilizes flat files and generates output in JSON format

I am in the process of developing a basic website using flat-file content management and a Vue.js front-end. My goal is to establish a specific file structure as outlined below: app - various vue files and folders - data.json - posts - - post1.md - - post ...

Display the data received from the client on the NodeJS server

I have a basic html file that includes the following snippet of javascript: <script type="text/javascript"> $.ajax({ url: 'http://192.168.X.X:8080', data: '{"data": "1"}', dataType: ...

Can you tell me the performance metrics displayed in the Vue devtools alongside the components?

Looking for insights or resources on a feature in the Vue Dev Tools. In the components pane, there are little red and yellow squares that seem to indicate performance of components. These squares only appear after I update certain components, such as a tex ...

Troubleshooting Angular Reactive Forms: Issue with Binding Dynamic Select Dropdown Value

I currently have two arrays of data: AssociatedPrincipals, which contains previously saved data, and ReferencePrincipals, which consists of static data to populate dropdown controls. I am facing difficulties in displaying/selecting the previous value from ...

Combining items from the identical array in pairs using distinct identifiers

I have an array containing double values. const data = [ -0.003,-8.178509172818559E-16, 0.002,-1.3576469946421737E-15, 0.007,-1.2329107629591376E-1] I am looking to utilize these values in react-vis. The necessary syntax for data insertion in react-vis ...

The issue of "Callback is not a function" arises within the selectize framework

Currently, I am working on a yii2-basic project and have implemented the selectize extension for my forms. However, when running this section of the code, an error is returned stating 'callback is not a function'. The field report_cp is a dropdo ...

What is the best way to extract information from a JSON object that includes a PHP array of objects?

I've successfully implemented an AJAX function for pagination links to dynamically load a new page of posts. However, I'm facing an issue with parsing a JSON object in this particular format. Here is the PHP style being passed as JSON: Array ( ...

Dynamic Data Powered jQuery Datatables

I have implemented a basic messaging system where I retrieve messages from the database using jQuery/AJAX and display them in a table. To enable pagination, I decided to utilize the DataTables plugin (https://datatables.net/). However, I am encountering d ...

The chosen choice is not able to be shown within the option tag

When attempting to filter options using JavaScript based on a selected item, I'm encountering issues. If the selected element contains 'CONTINUE' or 'BRACKET', it should be split into an array by space and only the first two indice ...

Incorporating words into the core of a pie chart: Highcharts

Is there a way to display the total value in the center of a pie chart? I've attempted some methods but haven't been successful. The goal is to show the sum of all y values. Input export const data = [ { y: 15, name: "Category 1&q ...

Challenges with asynchronous problems related to importing models utilizing promises in conjunction with the three.js

I'm currently struggling to resolve a promise in my script. The promise needs to be resolved when a function containing 3D file imports finishes importing, but I'm unsure how to make this happen. Is there a way to receive a signal or data from t ...

A feature that updates the value of a textarea by continually adding new data instead of replacing it

One common issue that I am facing involves setting the value of a textarea using a function. Initially, when I click the button to set the value, everything works fine. However, if I attempt to set the value again by choosing a different option from a lis ...

Remove a child node from its parent node in real-time

Currently, I am working on a project that involves adding and removing items as needed. The user interface can be seen in the image provided below: https://i.sstatic.net/Qhy2t.png Workflow: When the add icon is clicked, a new column is added for assignme ...

Is my Laravel application experiencing caching issues preventing real-time updates?

As I dive into learning AngularJS, I've encountered a strange issue where changes made in my JS files don't always seem to take effect. Even after seeing the GET request to the file in the console, the content remains unchanged. I can delete all ...

Unable to retrieve the data response

Trying to retrieve data from a mock online REST API and display it in the state, but encountering issues with the data not being properly stored and shown. Experimented with changing the state to an array or defining it as firstName: '', ... wit ...

Dynamic web page updates from server using an Ajax request

I have a JavaScript client application and an Express.js server. I am looking to update a page on my server with information sent through an AJAX call from my client application. I need the page to be updated in real-time. Here is the code snippet in my ...

Having trouble incorporating choreographer-js, an external JavaScript library, into my Nuxt project as it is not functioning correctly

Just starting out with vue.js and nuxt.js, I wanted to experiment with integrating an external JavaScript library into my nuxt.js project. My goal is to test out the functionality provided by this library: The library in question can be found here: https: ...

Sending an image dynamically as a prop to a child component

Within my parent component, I retrieve an object from an API which I later enhance with an image as a key/value pair. Subsequently, I pass this modified object to a child component for rendering. In order to accomplish this, I referred to the following pos ...