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

Identifying iOS Opera Mini browsers using JavaScript

Is there a way to prevent a specific script from running on the IOS Opera Mini browser? The navigator.UserAgent method is not providing clear identification for this browser. The returned string looks something like this: Mozilla/5.0 (iPhone; CPU iPhone O ...

Error encountered: Vue.js encountered an unexpected token, which is 'export'

Having an issue with Google location autocomplete, specifically this error: SyntaxError Unexpected token 'export' Here is the link to the functional code: https://codesandbox.io/s/nifty-bardeen-5eock ...

Encountered a Dojo error of "TypeError {stack: (...), message: "undefined is not a function"}" when attempting to display a gif during an ajax load

I've been attempting to display a loading gif while an ajax call is in progress. However, I encountered an error at the show statement and the console displayed: TypeError {stack: (...), message: "undefined is not a function"} Here's my code sn ...

Best practices for selecting checkboxes and transferring values to another page in PHP/HTML

Apologies for my lack of experience in PHP. I am in the process of creating a project without any knowledge of PHP. I have set up a database with a list of users and can display users based on specific information through a search. Each search query has a ...

Tips for arranging div elements in a grid-like matrix layout

I am facing a challenge in arranging multiple rectangular divs into a grid structure with 10 columns and 10 rows. The CSS styles for the top, bottom, left, or right positions must be in percentages to accommodate zoom in and out functionality without overl ...

The website flickers in and out as it loads

My site keeps flashing whenever it loads. Despite trying the solutions recommended in this stackoverflow post, I have had no success. Every page on my website loads a nav.html file using this code: $.get("nav.html", function(data){     $("#nav-placeho ...

Utilize React Native to showcase JSON data in a visually appealing way by organizing it into titles and corresponding lists for both

I created a live code on Expo.io to showcase JSON data categories as titles and the subs as a list. This code utilizes .map() to retrieve data from an array. import React, { useState } from 'react'; import { Text, View, StyleSheet, Button, FlatLi ...

Obtain the value of a range using JQuery

I made an attempt to retrieve the value of JQuery's range slider when it changes. Here is how I tried: On the HTML/PHP page: <div class="total"> <label for="">Total</label> <p><span class="monthrc"></span ...

When trying to submit a form, encountering an `Uncaught ReferenceError` due to calling ajax within

Attempting to trigger an ajax function within a form in order to retrieve a value for the dropdown. mypython.py @app.route('/new_data', methods = ['POST', 'GET']) def new_data(): #Filter data and return the data(data_lis ...

Customize hoverIntent to support touch events on mobile devices

Hello everyone. I've encountered an issue with hoverintent.js, a jQuery plugin that handles mouseOver events differently than usual. I am facing constraints where I can only modify the JavaScript of this plugin, but I need it to be compatible with to ...

Triggering a dynamically created event with the onchange event

I'm currently working on creating an input type file, and here is the code I have: var element = document.createElement("INPUT"); element.type = "file"; element.id = "element" + i; $("#media").append("<br>"); $("#media").append("<br>"); $ ...

Is it possible for me to generate c3js graphs dynamically?

Here is my current progress: <div id="chart"></div> <script> var names = <?php echo json_encode($array1) ?>; var count = <?php echo json_encode($array2) ?>; var x=0; while (names[x]!=null) ...

What could be causing jQuery animate to malfunction on mobile devices when a viewport is present?

Everything seems to be working fine on my desktop webpage, but when I try it on mobile, there is no scroll... $("HTML, BODY").animate({ scrollTop: 500 }, 1000); This post suggests that mobile devices may not scroll on the body, but on the vi ...

Exploring the world of two-dimensional arrays in D3 programming

I am interested in visualizing data obtained from the census data API, specifically from the ACS survey. The data is not in a typical JSON format, but rather as a two-dimensional array. It appears like this: [ [ “POPULATION”, “DATE”, ...

Ways to update the DOM following modifications to a data attribute

I'm currently working on a small CMS system that handles translations for static pages in multiple languages. The system refreshes and loads translations dynamically, but I've encountered some bugs that are proving difficult to resolve. One issue ...

Why do query values disappear when refreshing a page in Next.js? [Illustrative example provided]

In my current project, I am developing a simple Next Js application consisting of just two pages. index.tsx: import React from "react"; import Link from "next/link"; export default function Index() { return ( <di ...

The specified timeout elapsed without the jasmine async callback being invoked

Having recently ventured into Protractor and javascript, I've encountered a persistent error that none of the existing solutions seem to shed light on. The issue revolves around understanding async callbacks within my Page Object model implementation. ...

The Google map shifts beyond the perceived limits of the world

Is anyone else encountering an issue with Google Maps where you can now pan beyond the poles? It used to stop at the poles before, correct? The website I'm currently working on runs a location-based query on our server every time a user pans or zooms ...

"Ng-repeat function seems to be malfunctioning, although I am able to view

There seems to be an issue with ng-repeat when dealing with an array of objects: dummy.json [ {"name":"alpha", "data":[{"name":"Unit 1", "prereqs":[]}]}, {"name":"beta", "data":[{"name":"Unit 1", "prereqs":[]}]} ] While I am able to fetch the total ...

Accept only requests from my Chrome extension

I have successfully set up a NodeJS server with Express on DigitalOcean. My Chrome extension is able to make GET calls to the server without any issues. However, I am looking to enhance the security of the middleware below: // Add headers app.use(function ...