Using Vue.js to make asynchronous API requests using Axios

I am facing an issue with two versions of code, where the second version is not functioning as expected. I suspect it may be due to a contextual problem that I am unable to pinpoint.

The first version of the code works fine:

// Fist version (it works)
methods: {
      async sendDatas() {
            await this.$axios({
                method: 'post',
                url: '/url',
                data: {
                    email: this.email,
                },
            })
                .then((response) => {
                    console.log(response)
                })
                .catch((error) => {
                    console.log(error)
                })
        },

In the second version, I am unable to retrieve the response data in the callApi function:

sendDatas() {
            this.callApi(this.email)
                .then((response) => {
                    // Here "response" is "undefined"
                    console.log(response)
                })
                .catch((error) => {
                    console.log(error)
                })
        },

        async callApi(email) {
            await this.$axios({
                method: 'post',
                url: '/url',
                data: {
                    email,
                },
            })
                .then((response) => {
                    // Here "response" is ok"
                    console.log(response)
                })
                .catch((error) => {
                    console.log(error)
                })
        },

I cannot understand why I am unable to access the content of the response within the sendDatas function, considering the async callApi function returns a promise.

Your assistance in resolving this issue would be greatly appreciated :)

Answer №1

Your function callApi needs to be updated to return the promise instead of just making the API call:

    sendDatas() {
        this.callApi(this.email)
            .then((response) => {
                // The response may be undefined here
                console.log(response)
            })
            .catch((error) => {
                console.log(error)
            })
    },

    callApi(email) {
        return this.$axios({ // Make sure to add a return statement here
            method: 'post',
            url: '/url',
            data: {
                email,
            },
        })
            .then((response) => {
                // You'll get the correct response here
                console.log(response)
            })
            .catch((error) => {
                console.log(error)
            })
    },

Additionally, you can remove the await and async keywords since using then and catch is sufficient for handling the results.

Answer №2

It seems like there may be a duplication of promises in your code. You could try the following approach:

sendDatas() {
            this.callApi(this.email)
                .then((response) => {
                    // The value of "response" is currently "undefined"
                    console.log(response)
                })
                .catch((error) => {
                    console.log(error)
                });
        },

        async callApi(email) {
            // Removed one redundant `then` block
            return this.$axios({
                method: 'post',
                url: '/url',
                data: {
                    email,
                },
            });
        }

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

Why is fading out columns in an HTML table with jQuery's .fadeTo() method taking so long?

I am looking to implement a functionality where all cells in a column of my HTML table fade out when I click on a button located in the header of that column. I have written the following JavaScript code to achieve this: ... myDOMElement.find(".headerIcon ...

Variations in how words are organized within a sentence

Can you help me devise an algorithm to identify all possible combinations of word groupings in a sentence without changing the order of the words? For example, for the sentence "the test case phrase," the various combinations would include: ['the te ...

Leverage Vue.js to utilize dropdown selected data

I need help with populating additional form elements based on the selection of a record from a dropdown menu that contains response data obtained through an axios request. <multiselect v-model="order.orderJCname" id="orderJCname" name="orderJCname" :op ...

Different Angular 2 components are resolved by routes

Consider this scenario: Upon navigating to the URL /product/123, the goal is to display the ProductComponent. This is how it's currently configured: RouterModule.forRoot([ { path: 'product/:productId', ...

I encountered a permission error while trying to npm install, despite running the command with root privileges

After running npm install as root, I am still encountering permission errors. This is unfamiliar territory for me. I have attempted using chmod -R 777 *, and chown nobody:nogroup -R * within the project folder, but to no avail. Here's the specific er ...

The script ceased functioning immediately following the inclusion of a case-insensitive search feature and interactive images

In the process of creating my inaugural project featuring a collection of images, I wanted to include a filter/search bar at the top. This bar would dynamically filter the displayed pictures based on user input. For example, typing "Aatrox" into the search ...

Creating routes with hyphens from page names in Nuxt: A step-by-step guide

I'm trying to create routes like privacy-policy and terms-condition in Nuxt without the page names being capitalized as Privacy-Policy or Terms-Condition. Is there a straightforward method to achieve this without needing to customize the route? ...

Successive pressing actions

I am struggling to grasp a unique Javascript event scenario. To see an example of this, please visit http://jsfiddle.net/UFL7X/ Upon clicking the yellow box for the first time, I expected only the first click event handler to be called and turn the large ...

"Enhancing Functionality: A Detailed Guide on Callback Functions in Express

Currently, I am expanding my coding skills by learning express/Node, transitioning from C and PHP/MySQL. The MDN tutorial on express has been incredibly helpful in my learning journey, making everything straightforward. Thanks to the Mozilla teaching team, ...

Set panning value back to default in Ionic

I need assistance with resetting the panning value. Essentially, I would like the panning value to return to 0 when it reaches -130. Below is my code snippet: swipeEvent($e) { if ($e.deltaX <= -130) { document.getElementById("button").click(); ...

Managing a database update when server actions involve various form types

My UI dashboard contains multiple forms like "edit title" and "edit description", each with just one input element. I am looking to streamline database updates and server actions in next js 14, utilizing useFormState on the front end. While I have achieve ...

When transmitting an ajax POST FormData object, the key and value may not be transmitted as originally configured

In my code, I am setting up a FormData object like this: const formData = new FormData(); formData.append('id', '12345678'); Next, I make a POST request using angular HttpClient. However, when I use Postman to debug the reques ...

JQuery UI Autocomplete: Results, Ctrl + A and Delete

I am currently designing a form that allows users to add members to a project. Only members with existing profiles in the system can be added. The form includes an input field for the member's name and a select box for their position, which is initial ...

Which JavaScript objects contain the addEventListener method within their prototype?

I am aware of the following: Element.prototype.addEventListener Window.prototype.addEventListener Document.prototype.addEventListener Are there any more? ...

What is the reasoning behind storing type definitions in the @types namespace within npm?

Have you ever wondered why type definitions in npm are stored under the @types namespace which isn't directly linked to a specific organization, user, or library? Wouldn't it make more sense for npm libraries to have their types located under @[o ...

Ensuring Input Integrity: Utilizing HTML and Javascript to Block Unfilled Form Submissions

Currently, I am working on developing a registration page using HTML and JavaScript. Although I have added the 'required' tag in HTML to prevent users from submitting empty input fields, I noticed that users can bypass this restriction by simply ...

What steps should be followed to incorporate a user image and name when a user submits a comment in a functional JavaScript comments section?

After stumbling upon a comment box submitted by the user Rick Hitchcock (link here), I realized that I need to incorporate a generic user image and a username (could be anonymous) when a user submits a comment. Unfortunately, I am clueless on how to achiev ...

Discovering the process of iterating through values from multiple arrays of objects and applying them to a new response in Angular 8

Received the following data from an API response: const apiResponse = { "factoryId": "A_0421", "loss": [ { "lossType": "Planned Stoppage Time", "duration": ...

What tool can be used for formatting and syntax highlighting when working with ejs (embedded javascript) templates?

When working on my project, I utilize EJS as the express templating engine. While it is user-friendly and efficient, I have encountered difficulties when it comes to editing files - the text highlighting could be better, and I have not been able to find an ...

I successfully coded a function without utilizing the function key, but unfortunately I am encountering difficulties when trying to output the

I have created a function without using the function keyword. The function should take the age above 15 and push it into an array. I have been able to do that, but I am struggling to print the result. Can anyone help me with this? my code <script> ...