Creating a Nuxt project and integrating the Axios module

I'm running into an issue where I'm not receiving any data from my Axios async calls. I've configured my calls in my Nuxt config as follows:

modules: [
  '@nuxtjs/axios',
],

And in my component, it's set up like this:

<template>
    <div>
        {{audioUrls}}
        {{ip}}
    </div>
</template>

<script>
export default {
    name: "Audio",
    data() {
        return {
            audioUrls: null,
        }
    },
    async asyncData({ $axios }) {
        const ip = await $axios.get('http://icanhazip.com')
        return { ip }
    },
    mounted() {
        this.audioUrls = this.asyncData()
    }
}
</script>

Despite no errors being reported, I haven't been able to receive any data in my app. Am I overlooking something important?

Answer №1

It seems like there is a mistake in how you are handling the return value of $axios.get(). Make sure to destructure the data properly:

// ❌ Incorrect usage: $axios.get() returns a Response,
// where the data property holds the actual response data
const ip = await $axios.get(...)
return { ip }

// ✅ Correct approach
const { data: ip } = await $axios.get(...)
return { ip }

Additionally, it appears that you are attempting to utilize asyncData() within a component, but components do not support asyncData(). You can either move asyncData() to a page file (e.g., pages/index.vue) or use fetch() inside the component, which functions similarly. Remember to initialize ip in the data() method:

// MyComponent.vue
export default {
  data() {
    return {
      ip: '',
    }
  },
  async fetch() {
    const { data } = await this.$axios.get('http://icanhazip.com')
    this.ip = data
  }
}

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

Add the latest value to the end of the selection option

How can I append a new value at the end of an option select box, ensuring that the number continues instead of starting from 1? var n_standard = 1; function removeStandard() { var select = document.getElementById('selectBoxStandard'); for ...

Leveraging Async/Await to track error counts across three distinct loops, each invoking an asynchronous function in every iteration

While I have experience with Callbacks, Async/Await and Promises are new concepts to me. In my node.JS server project, I am faced with the challenge of counting errors generated by thousands of asynchronous calls from three different async functions. My g ...

Exploring the OAuth 2.0 integration with OpenID Connect, Loopback, and Keycloak

I'm having trouble establishing a connection to Keycloak from Loopback. I've been experimenting with the keycloak-connect library available at: https://github.com/keycloak/keycloak-nodejs-connect This snippet shows my current implementation in ...

Leverage async and await features in TypeScript aiming at ES5 compatibility

Currently working on a TypeScript project that is set to target ES5, I am exploring the feasibility of incorporating async/await functionality. Syntactically, the TypeScript compiler is able to transpile the code without issues. However, it has come to my ...

Navigating through a JSON data structure

The information retrieved from the PHP page appears as follows: [{ "id": "1", "name": null, "startdate": "2012-07-20", "starttime": "09:53:02", "enddate": "2012-07-20", "endtime": "09:54:10", "duration": "01:00:00", "feedba ...

Issue encountered: Unable to load resource - ajax file upload failed due to net::ERR_SSL_BAD_RECORD_MAC_ALERT error

I've implemented an AJAX form file upload using jQuery. After testing my code across multiple computers and browsers, I've encountered an issue on one Windows 8 machine running Chrome where the upload functionality fails with the following error ...

How can I stop the hover event on a series in Highcharts from triggering a hover event on the nearest point (marker)?

When hovering over the series line on a date-time chart, the default behavior is to trigger the hover event on the nearest point of the series. However, I only want to trigger the hover event on the markers (points), not the series itself. If I use stopP ...

A guide on crafting OR queries in Elasticsearch using Node.js

I currently have a document structured like this: Sample document, [ { "_index": "xpertdox", "_type": "disease", "_id": "Ectopic Heartbeat", "_score": 24.650267, "_source": { "category": "Condition", "name": "Ectopic ...

Invoke a jQuery method in a dynamic manner

Is it possible to achieve the following? var todo = "text"; $this.eval(todo).split(/\b[\s,\.-:;]*/).length; The desired function is: $this.text().split(/\b[\s,\.-:;]*/).length; I'm struggling to find a solution... Ca ...

Could you please direct me to the section in the ECMAScript documentation that specifies the behavior of a resolved promise with its [[Promise

My objective is to compare the behavior of a promise's resolve function with the corresponding process outlined in the ECMAScript specification. Specifically, I am interested in understanding how the resolve function behaves when called with an object ...

In JavaScript, the event.defaultPrevented property will never be set to true

I've been experimenting with events in my script, but I'm struggling to understand the functionality of event.preventDefault()/event.defaultPrevented: var e = new Event('test'); e.defaultPrevented; > false e.preventDefault(); e.d ...

How to retrieve the content/value from a textfield and checkbox using HTML

I'm encountering an issue with my HTML code where I am unable to extract data from the HTML file to TS. My goal is to store all the information and send it to my database. Here is a snippet of the HTML: <h3>Part 1 : General Information</h3 ...

Steps for signing up for a store module

I understand that Vuex allows us to use store.subscribe and provide a callback that is triggered each time there is a change in the store. Within my application, I have a store with multiple modules and I am interested in subscribing only to a specific mo ...

Revolutionary Pageslide Feature in JQuery Mobile: Introducing the Cutting-Edge

Let me share my story: I am looking to incorporate a new facebook-style menu on the left side of my webapp screen. Although I find it really nice, my lack of expertise in css and css3 is proving to be a challenge. After searching for a few hours, I stumb ...

Tips for saving an array of objects in local storage and transferring it from one file to another

Recently delving into the world of localstorage, I've encountered an issue while attempting to store JSON data in one file and retrieve it in another. The JSON data below was fetched from a URL, and my goal is to obtain all the feed objects in the oth ...

Using a try block inside another try block to handle various errors is a common practice in JavaScript

In an effort to efficiently debug my code and identify the location of errors, I have implemented a try-catch within a try block. Here is a snippet of the code: for (const searchUrl of savedSearchUrls) { console.log("here"); // function will get ...

Navigating through the labyrinth of SSH documentation

I'm looking to develop a lightweight SSH protocol client implementation for node.js. The documentation at is causing confusion. It lacks a comprehensive example of the key exchange process, making it difficult to understand how all the components fi ...

How can one HTML form be used to request a unique identifier from the user, retrieve a record from the database, parse it into JSON format, and then populate an HTML page form using the

As someone who isn't an expert in any specific coding language, I have a knack for piecing things together to make them work. However, my current challenge is stretching my technical abilities a bit too far. Here's what I'm trying to achieve ...

Is there a way to incorporate React into JavaScript files without using NodeJs?

Want to know how to incorporate a react file into Javascript files without using any library or nodeJs? Here is a snippet of my code: main.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <title> ...

Issue 1054 - The variable being used as a field in the WHERE clause is being interpreted as a column

While attempting to update a mysql database, I encountered an error where the variable 'id', which is used as a field in the WHERE clause, is being interpreted as a column name. Am I misreading this? What needs to be corrected in order for this q ...