Ensure that you patiently wait for the axios method to finish execution before moving on to the

I am currently learning vue.js and struggling with the concept of promises. I need to initialize a variable with data from an API call, but I want to ensure that the Axios call is generic:

{
  data: {
    list: [],
  },
  methods: {
    ShowList: function () {
      return this.Axios_GET('/api/Api_Store').then(items => {
        this.list = items;
      });
    },

    Axios_GET: function (apiurl) {
      // I want this method to be reusable without binding variables inside it
      this.StartProgress();
      axios({ method: 'get', url: apiurl }).then((response) => {
        this.StopProgress();
        return Response.data;

      }).catch((error) => {
        this.StopProgress();
      }).then(function () {

      });
    },
  }
};

However, when I attempt to use ShowList, I encounter the following error:

Error in mounted hook: "TypeError: Cannot read property 'then' of undefined"

I wish to write the ShowList function to retrieve data from the API like this (in theory)

this.list = this.Axios_GET('/api/Api_Store') 

Note: The functions StartProgress and StopProgress are already defined and operational.

Answer №1

{
  info: {
    items: [],
  },
  actions: {
    DisplayItems: function () {
      return this.RequestData('/api/Api_Store').then(items => {
        this.items = items;
      });
    },

    RequestData: function (apiurl) {
      // This method is designed to be reusable and not require variable binding within
      this.StartLoading();
      axios({ method: 'get', url: apiurl }).then((response) => {
        this.StopLoading();
        return response.data; // Modified to use response.data rather than Response.data for consistency

      }).catch((error) => {
        this.StopLoading();
      }).then(function () {

      });
    },
  }
};

Answer №2

Learn how to implement promise chaining in your code.

{
  data: {
    collection: [],
  },
  methods: {
    DisplayCollection: function() {
      return this.FetchData('/api/Api_Store').then(items => {
        this.collection = items || [];
      });
    },

    FetchData: function(apiurl) {
      this.StartLoading();
      return axios({
          method: 'get',
          url: apiurl
        })
        .then(response => response.data)
        .catch((error) => {
          // handle error if necessary;
        }).finally(() => {
          this.StopLoading();
        });
    },
  }
};

Answer №3

Make sure to remove the unnecessary then() function at the end of the axios promise chain and handle errors by using Promise.reject() in the catch block to propagate them. Remember to return the axios promise chain from the function.

If you don't properly handle the error, the promise will be resolved instead of rejected, which can cause issues in your ShowList function.

Check out the revised code below:

{
  data() {
    return {
      list: []
    };
  },
  methods: {
    ShowList: function () {
      return this.Axios_GET('/api/Api_Store').then(items => {
        this.list = items;
      })
      .catch((err) => {
        // Handle errors here (Display a warning or error)
        this.list = [];
      });
    },

    Axios_GET: function (apiurl) {
      
      this.StartProgress();
      
      // Don't forget to RETURN.
      return axios({ method: 'get', url: apiurl }).then((response) => {
        this.StopProgress();
        
        return response.data;
      }).catch((error) => {
        this.StopProgress();

        return Promise.reject(error);
      });
    },
  }
};

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

Converting a JavaScript variable into an xls or csv file

My application currently uses Javascript for calculations and data plotting, but I want to give users the ability to download the data as a csv or xls file. Is there a way in Javascript or another method where users can click a button, enter a filename, an ...

Replace the facebook plugin using JQuery libraries

Does anyone know how to remove the like button on top of the 'Like box' Facebook plugin using JQuery? I have imported the like box from Facebook and I want to eliminate this like button, but Facebook does not allow me to do so. Therefore, I am t ...

What is the best way to receive the result of an asynchronous function as an input and showcase it using express?

I have recently started learning about node and express My goal is to create an API that can fetch data from an external source and use that data for my application Is there a way to retrieve the result of an asynchronous method and display it using the ...

Navigating additional information in D3 Node Link Force diagram

Recently delving into the world of D3, I have been pleasantly surprised by its capabilities and decided to experiment with the Directional Force Layout. My Objective Initially, I successfully created a json object using a for loop to prepare my items for ...

Troubleshooting the non-functional asynchronous function

After starting to use redis with node (specifically the node_redis module), I decided to wrap my retrieval code for debugging and DRY principles. However, I encountered an issue where my new function wasn't working as expected. As someone who is stil ...

How to Implement Jquery Confirm in Laravel Form Opening?

I've set up a Form using the Laravel Form package. {!! Form::open(['action' => ['Test\\BlogController@destroy', $thread->id], 'method' => 'delete', 'onsubmit' => 'Confirm() ...

Troubleshooting Bootstrap select box design discrepancies

Currently revamping a website and encountered an unusual issue with select boxes. There seems to be an overlapping white space where the option values should be. Here's a visual reference: View Image of Select Box Issue Utilizing Bootstrap for the re ...

Successful Ajax response notification

I am new to using ajax and I want to implement a .post method with an if condition to notify the user of its success or failure. Here is my code for .post: $.post("ajaxRegistering.php",{ name: name, lastname: lastname, ...

Ways to categorize items using JQuery based on their hierarchical structure

I am looking to organize the following HTML content: <h2>State the Issue  </h2> <h3>Provide information about your objective</h3> <h3>Share any error messages received</h3> <h2>Outline Your Attempts  ...

Testing-library does not seem to recognize SFC styles

I've been working on implementing unit tests in our Vue codebase, but I'm running into some trouble when it comes to testing the visibility of an element. Even though I render the component as per usual and following the examples provided in the ...

What is the best way to retrieve a value from a function that contains multiple nested functions in Javascript?

The issue at hand is my struggle to extract a value from a nested method and utilize it outside of its parent method. I am aiming for the output of "console.log(someObjects[i].valueChecker);" to display either "true" or "false," but instead, it simply retu ...

Creating a column that adjusts dynamically in PDFMAKE

Currently, I am utilizing PdfMake within my VueJS app to generate PDFs. I am curious as to whether it is possible for me to have control over the columns displayed in my template by using the data that is being printed as a variable. I am aiming to achiev ...

When using the Ng --version command on a development package, it throws an error

I encounter an error with a development package when cloning a repository. I would greatly appreciate any advice on how to resolve this issue. https://i.stack.imgur.com/DBp5r.png ...

The OutlinedInput component from Material-UI seems to be struggling to display the startAdornment

Below is the code snippet. The start adornment is not displaying in the textfield, and there is no text appearing on the label. <InputLabel>Mobile Number</InputLabel> <OutlinedInput variant="outlined" ...

Changing colors in the rows of a table

Here is a fiddle I created to demonstrate my issue. https://jsfiddle.net/7w3c384f/8/ In the fiddle, you can see that my numbered list has alternating colors achieved through the following jQuery code: $(document).ready(function(){ $("tr:even").css("ba ...

Use RxJS chaining to transform an observable of `File` objects into an observable of strings encoded in base64

I have successfully written code that converts my File object to base64: let reader = new FileReader(); reader.readAsDataURL(myFile); reader.onload = () => { let resultStrOrArrayBuf = reader.result; if (!(resultStrOrArrayBuf ...

Sorting an array of Material-UI's <TableRow> alphabetically using ReactJS and Material-UI. How to do it!

I am currently utilizing Material-UI's <Table> and <TableRow> components by rendering an array of <TableRow>s using the .map() method. Each <TableRow> contains a <TableRowColumn> representing a first name, for example: &l ...

What is the best way to create an array within an object in JavaScript?

Here is the code snippet I'm working with: var Memory ={ personAbove: "someone", words: wordsMem = [] <<<<<this part is not functioning properly } I need help figuring out how to make it function correctly. Specific ...

Adaptable Image Functionality in Jquery Carousel

I've encountered an issue with my images within a jquery slider. While the slider itself is functioning properly, I am facing a couple of challenges. Initially, I aimed to make the images responsive, but upon removing the height property, the content ...

Unable to interact with buttons located in the title bar of the Electron application

I am currently working on developing a basic Text Editor using Electron. I am facing an issue with adding a custom title bar where the buttons are not clickable. To try and fix this issue, I have included an onclick tag to the buttons in my code. main.js ...