Is it possible to retrieve an array using axios?

Currently, I am exploring computed properties in Vue.js.

One of the computed methods I am working on involves making a request to an axios API to retrieve an array after applying some logic within the promise.

computed: {
    filteredTrips: function () {
        var filtered = this.trips;
        if(this.filters_by.indexOf('monitor')>=0) filtered = this.filter(filtered, this.BusMonitorID,'BusMonitorID');
        if(this.filters_by.indexOf('route')>=0) filtered =  this.filter(filtered,  this.TourID,'TourID');
        if(this.filtered_count==0) return this.getFilteredTrips(); //This is the axios method to get an array
        return filtered;
    }
},
methods: {
    getFilteredTrips:function(){
      var resource = base_url+'report/transport/filter';
      var self = this;
      axios.post(resource, $.param({filters:this.filters})).then(function(response) {
        // here i'm performing some logics to make self.trips

        self.trips.push(data[trip]); //push data to self.trips

        return self.trips; // i need to return this array
      }).catch(function(response) {
            // error callback
        })
     }
}

My challenge lies in the fact that getFilteredTrips() does not return the self.trips array. How can I achieve this using axios and JavaScript?

Answer №1

When working with computed properties, it's important to note that they cannot handle asynchronous tasks such as backend calls. In such cases, it is recommended to use methods instead. Consider using the method getFilteredTrips in this scenario.

For this purpose, you can define a data property called filteredTrips and update it within the getFilteredTrips function. Here is an example of how your code might look:

data:{
  return {
    filteredTrips: []
  }
},
computed: {
    filteredTripsComputed: function () {
        var filtered = this.trips;
        if(this.filters_by.indexOf('monitor')>=0) filtered = this.filter(filtered, this.BusMonitorID,'BusMonitorID');
        if(this.filters_by.indexOf('route')>=0) filtered =  this.filter(filtered,  this.TourID,'TourID');
        return filtered;
    }
},
methods: {
    filteredTrips:function(){
        if(this.filtered_count==0) return this.getFilteredTrips(); 
         return this.filteredTripsComputed;
    }
    getFilteredTrips:function(){
      var resource = base_url+'report/transport/filter';
      var self = this;
      axios.post(resource, $.param({filters:this.filters})).then(function(response) {
        // Execute necessary logic here to populate self.trips

        self.trips.push(data[trip]); // Add data to self.trips

        self.filteredTrips = self.trips; // Return the updated array
      }).catch(function(response) {
            // Handle errors here
        })
     }
}

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

Navigating through error messages in NextJs 14 can be tricky, especially when faced with the dreaded "ReferenceError: document not defined" or "prerendering error". It's vital to pinpoint exactly which page

When attempting to run the build on my Next.js application, I encountered an error message that is not very informative given the number of files/pages in my project. How can I pinpoint the exact location of this error and determine the root cause? The pro ...

The "npm start" command encountered an issue: script "start" is

I'm encountering an issue when attempting to run my node application using the npm start command in Visual Studio Code. Any assistance would be greatly appreciated! Here is the content of my package.json file: { "name": "bloggin-site ...

Unexpected date outcomes in JavaScript when using a similar date format

Why is it that the first input produces the correct result, while the second input displays a time that is 5 hours behind? new Date("2000-1-1") Sat Jan 01 2000 00:00:00 GMT-0500 (EST) new Date("2000-01-01") Fri Dec 31 1999 19:00:00 GMT-0500 (EST) How can ...

Having difficulty accessing a private channel with Laravel and Vue.js due to pusher integration

I've successfully set up a notification system and everything is working fine when I send notifications to Pusher. However, I encounter an error when trying to listen on a private channel. Below is the code from my bootstrap.js file in Laravel-Echo: ...

Using Vue.js to mark a checkbox as selected

I've searched extensively and tried various combinations, but I'm unable to initialize my checkboxes as checked. For example: <ul class="object administrator-checkbox-list"> <li v-for="module in modules"> <label v-bin ...

It appears that the font in style.css is not being updated properly and seems to resemble

My issue lies within my CSS code. The text on my website is not displaying correctly and seems to be ignoring the styling that I have applied. Even though I have used similar styling on other buttons which look fine, this specific text element is causing p ...

Displaying HTML content from a Vuejs response within a Dialog box

After receiving a response from the server via a REST request in HTML format, I have saved it in a data:[] variable. When I log this data on the console, it appears as raw HTML code. This reply is currently stored as a String, and my challenge now is to co ...

Can you explain the process of accessing data from [[PromiseValue]] while utilizing React hooks?

My current challenge involves fetching data from an API and utilizing it in various components through the Context API. The issue arises when I receive a response, but it's wrapped under a Promise.[[PromiseValue]]. How can I properly fetch this data ...

"Implementing a responsive design with a background image and radial gradient - how to

The image currently in use: https://i.stack.imgur.com/piK6l.jpg Here is how I've implemented it using Vue.js, Bootstrap, and CSS: Code Snippet <div class="landing"> <div class="container text-white details h-100"> ...

Passport is raising a "missing credentials" error upon return

Hello everyone! I'm currently working on a password reset form and encountering an issue. When I submit the email in my POST form, I'm seeing a frustrating "Missing credentials" error message. This is preventing me from implementing the strategy ...

Bringing in SCSS using Typescript, React, and Webpack

I am trying to utilize .scss classes by importing them and applying them to the className property of a React component. Here is the structure of my project : root/ ... config/ ... webpack.config.js src/ ... global.d.ts app/ ...

Learn how to efficiently transfer a dynamic subtitle text value from an HTML5 video player to a database

I have successfully developed an HTML5 video player with subtitles. Currently, my goal is to allow the user to submit the subtitle text at a specific timestamp to a database. Despite trying various methods, I am facing challenges in fetching the subtitle t ...

Obtaining the translated text from the script in Vue JS using Vue Translate

My code currently looks something like this: <template> <div> {{ text }} </div> </template> <script> export default { data: () => ({ text: 'Hello world' }) } </script> I am tryin ...

angular5: The ngFor directive will only function properly after the second button click

Here is my current situation: 1) When the user inputs a keyword in a text field and clicks on the search icon, it triggers an HTTP request to retrieve the data. 2) The retrieved data is then rendered in HTML using ngFor. The issue I am facing is that up ...

Extract the image URL from a JSON API

I'm struggling to retrieve an image URL from a Wordpress JSON API and populate an image tag with it. Below is the code that isn't working for me: $(document).ready(function() { $.getJSON('http://interelgroup.com/api/get_post/?post_id=46 ...

`No valid form submission when radio buttons used in AngularJS`

Within my form, I have a single input text field that is required (ng-required="true") and a group of radio buttons (each with ng-model="House.window" and ng-required="!House.window"). Interestingly, I've discovered that if I select a radio button fir ...

My iPad is acting up and the .click() function seems to be malfunctioning, but only within

Currently dealing with a perplexing and frustrating issue - I've implemented a .click() event in a view of my backbone.js application (my first time doing so), and while it works perfectly in all desktop browsers, it simply refuses to work on the iPad ...

Change the class name using jQuery when scrolling

Currently utilizing bootstrap as my primary css framework. My goal is to dynamically toggle a class on the navbar once the user scrolls past the prominent header image located at the top of the website. UPDATE: Admitting I made an error and had a momenta ...

What is the correct way to test setInterval() statements within Angular?

Here is a simple code snippet I am working on: public async authenticate(username: string, password: string) { const authenticationResponse = await this.dataProvider.authenticate(username, password); if (authenticationResponse.result.code == 0) { ...

Steps for adding an onclick function to a collection of div elements

My current project involves utilizing the Flickr API and I am interested in creating a popup div that opens when clicking on each image. The goal is to display the image in a larger form, similar to how it's done using Fancybox. I'm looking for ...