What is the best way to retrieve an axios response in Vue.js using a v-on:click event with asynchronous functions and try/catch blocks?

Can someone assist me? I am attempting to retrieve an object response from an API using axios in an async function with try and catch blocks. Currently, when I make the request, I receive: Promise { pending }. How can I access my object?

Here is a snippet of the template:

<div class="div-search-city">
  <input v-model="inputCity" placeholder="insert city name"/>
  <button id="buttonCity" @click="get()">Search city</button>
</div>

And here is part of the script:

<script>
import myFunction from './js/service.js';

export default {
  name: 'Input',
  data () {
    return {
      myData: {}
    }
  },
  methods: {
    get(){
      this.myData = myFunction.axiosRequest(this.inputCity);
      console.log(this.myData);
    }
  }
}
</script>

Additionally, this excerpt shows the contents of my service.js file:

const axios = require('axios');

var myFunctions = {
  async axiosRequest(city){
    var options = {
        method: 'GET',
        url: 'https://api.waqi.info/feed/' + city + '/',
        params: {
            token: 'a1d2e0ee074e48f8bf....................'
        }
    };
    try {
      let response = await axios.request(options);
      return response
    }catch (error) {
       console.error(error)
    }
  }
}

export default myFunctions

Thank you for your help.

Answer №1

To achieve this, my approach involves returning the promise from the service.js file and using await on the client side. Once the await is resolved, you can assign the data to the specified variable within the Vue component.

Answer №2

<script>
import fetchData from './js/fetchData.js';

export default {
  name: 'UserInput',
  data () {
    return {
      userData: {},
      
    }
  },
  methods: {
    async fetchData(){
      this.userData = await fetchData.getData(this.inputValue);
      console.log(this.userData);
      
    },
  }
  
}
</script>

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

Choose one distinctive icon from a multitude - vue.js

I'm feeling really confused at the moment. I have a list of items, each with a heart-shaped "like" button. When I click on the icon, I want the color to change. However, the issue is that all the hearts change color instead of just the one I clicked o ...

Troubles arise when trying to compile Typescript and React with esbuild

I set out to create a new package and upload it to npm, starting with a demo package first. I began by using this repository as a foundation: https://github.com/wobsoriano/vite-react-tailwind-starter After that, I made updates to the build script: " ...

Enhance the sequence of tweens by triggering them sequentially in response to rapid UI events

I am currently working on my three.js app setup and I am facing a challenge with creating a smooth transition between two models. The desired effect is to have the first model quickly scale down to zero, followed by the second model scaling up from zero t ...

Contrasting $route.current.pathParams with $routeParams

I'm currently attempting to update a URL without having to refresh my page, and I came across this solution that I am working with: https://github.com/angular/angular.js/issues/1699#issuecomment-45048054 Upon further testing, I found that the followi ...

Trouble retrieving data from a JSON array with AngularJS ng-repeat and AJAX

I'm currently using Angular Js with ajax, but I'm having trouble retrieving output from a JSON array when using ng-repeat. When I try to display the data, all I see is [Object object] in the alert message. However, if I use $scope.names = respons ...

Authenticate yourself as a user or an organization on mongodb

I am currently developing an application that requires user registration and login, as well as organization registration and login. I have implemented the use of Node.js Passport with a local strategy for authentication. While I have successfully created t ...

Time Flies Zone - Date Error

The code snippet provided demonstrates that calling moment.tz('30 3 14:59', 'w d HH:mm', 'America/Los_Angeles'); successfully parses the date and time. However, changing the time to anything between 15:00 and 23:59 results in ...

Tips for implementing Vue in production mode with vue.esm-bundler.js

Currently, I am utilizing Vue 3 with webpack and loading it using vue.esm-bundler.js due to the presence of in-dom templates. The documentation mentions that when using a bundler, you need to "Leaves prod/dev branches with process.env.NODE_ENV guards (mus ...

The double click feature is not functioning properly when used in conjunction with the selectpicker Boostrap

<select class= "selectpicker" id="cus_id"> <option value="654" >test1</option> <option value="6877" >test2</option> <option value="8687" >test3</option> </select ...

Inconsistencies in JavaScript comparison across various web browsers

Here is a snippet from my JavaScript code var dataList = eval(strArray[0]); for (i = 0; i < dataList.length; i++) { console.log(((dataList[i].isFollowed == 0) ? "Follow" : "Unfollow")); } However, this code exhibits varying behavio ...

Create a feature that allows users to search as they navigate the map using Leaflet

Exploring the idea of incorporating a dynamic "Search as I move the map" feature similar to Airbnb using Leaflet. Striving to strike a balance between loading data relevant to the displayed portion of the map and minimizing unnecessary API requests trigger ...

Utilizing the power of Vue 2 and NuxtJS to effortlessly customize the appearance of child components

I am currently working on a Nuxt.js project (still using Vue 2) that consists of two components. I am trying to override the child style with the parent's style, but the ::v-deep pseudo selector doesn't seem to be effective. Regardless of my eff ...

What is the best way to patiently wait for lines to be printed out one by one

I am in the process of creating my own personal website with a terminal-style design, and I'm looking to showcase a welcome banner followed by a welcoming message. The effect I have in mind involves lines appearing individually from top to bottom and ...

Trigger animation when the scroll position reaches 0.52 in Next.js using framer-motion

I’m working on a landing page and I have a section where I’d like to create a simple opacity animation using framer-motion. The issue is that these animations typically trigger as soon as you land on the page, but I want them to be based on scroll pos ...

Which is better for a jQuery/Ajax Login Box: JSONP or CORS?

To create a login box that meets the specified criteria, the following must be taken into consideration: Develop it as a versatile UI Component that can be utilized in various sections of a website Allow for multiple instances of this component to coexis ...

Implement a specific focus() method on a reference element that is being iterated through using v

My objective is to have the button hidden and the corresponding input displayed and focused when the button is clicked. let tagIdBeingEdited = ref(0) let buttons = ref([]) let inputs = ref([]) async function toggleTagInput(id:number, index:number ) { ...

Difficulty arises when collapsed text in Bootstrap clashes with the footer design

Hey there! I'm working on this website using Bootstrap, and I've encountered a problem. When you click the "See Wikipedia" button, the content expands and overlaps the footer in a strange way without changing the page height. I've tried adju ...

Include a requirement within an application/ld+json formatted script

I have a task to create an application using a script in the js+json format. It is crucial to include the person schema, which signals to Google and other search engines how to effectively interpret the structure of the page and its content. My current cod ...

What is the process for relocating a marker to a predicted address from the AutoComplete API

My attempt to achieve this is through the following lines of code: var marker = new google.maps.Marker({ position: geolocation, animation: google.maps.Animation.BOUNCE }); marker.setPosition(geolocation); The code snippet above, which ...

Is it feasible to develop a functional computer interface using threejs?

Is it feasible to integrate a window into threejs that could facilitate the use of standard desktop applications (such as code editors) within the virtual scene? Please note: This is being implemented within a custom application or a node-webkit environme ...