Using Axios in a VUE application to handle response data

I've been working on a VUE application and I'm currently exploring how to handle post responses with Axios. Initially, I used vue-router for fetching data but decided to give Axios a try.

Axios code:

methods: {
        sendForm () {
            console.log("submitHandler called - success!");

            const payload = {
    
                first_name: this.event.firstName,
                last_name: this.event.lastName,
                email: this.event.email,
                password: this.event.password,
                name: this.event.agencyName,
                abbreviation: this.event.abbreviation,
                type: this.event.agencyType,
                address: this.event.agencyAddress,
                city: this.event.agencyCity,
                state: this.event.state,
                zipcode: this.event.zipcode,
                phone: this.event.phone,

            }

            axios.post(process.env.VUE_APP_API_URL+"/agency/add",payload)
                .then(function (response) {

                    console.log('Response', response)

                            //reformat returned expiration date for displaying on webpage
                            console.log("Expiry date:", response.data.data.agency.expiry);
                            let expd = dayjs(response.data.data.agency.expiry).format("dddd, MMMM D YYYY");

                            //Write retunred values to storeage
                            store.user = {
                                id: response.data.data.user.id,
                                first_name: response.data.data.user.first_name,
                                last_name: response.data.data.user.last_name,
                                email: response.data.data.user.email,
                                agency_name: response.data.data.agency.name,
                                expiry_date: expd,
                            }

                            router.push("/SignUpConfirm");

                })
                    .catch(function (error) {
                    console.log('Error', error.message);

                     Swal.fire({
                    icon: 'error',
                    title: 'Oops...',
                    text: error.message,
                    })

                })
                 }

        }

The issue/question I have is that I need to use "response.data.data.foo" to access the desired response, whereas with the built-in view router, I only needed to use "data.foo"

Vue-router option:

methods: {
        submitHandler() {
            console.log("submitHandler called - success!");

            const payload = {
    
                first_name: this.firstName,
                last_name: this.lastName,
                email: this.email,
                password: this.password,
                agency_name: this.agencyName,
                abbreviation: this.abbreviation,
                agency_type: this.agencyType,
                agency_address: this.agencyAddress,
                agency_city: this.agencyCity,
                state: this.state,
                zipcode: this.zipcode,
                phone: this.phone,

            }

            const requestOptions = {
                method: "POST",
                body: JSON.stringify(payload),
            }

            fetch(process.env.VUE_APP_API_URL+"/agency/add", requestOptions)
            .then((response) => response.json())
            .then((response) => {
                if (response.error) {
                    console.log("Error:", response.message);

                     Swal.fire({
                    icon: 'error',
                    title: 'Oops...',
                    text: response.message,
                    })

                } else {
                    //reformat returned expiration date for displaying on webpage
                    console.log("Expiry date:", response.data.agency.expiry);
                    let expd = dayjs(response.data.agency.expiry).format("dddd, MMMM D YYYY");

                    //Write retunred values to storeage
                    store.user = {
                        id: response.data.user.id,
                        first_name: response.data.user.first_name,
                        last_name: response.data.user.last_name,
                        email: response.data.user.email,
                        agency_name: response.data.agency.name,
                        expiry_date: expd,
                    }

                    router.push("/SignUpConfirm");
                }
            })
        }
    }

Answer â„–1

Your API response may look something like this (once you've parsed the JSON)

{
    data: {
        user: {
            ......
        }        
    }
}

For better understanding, let's say it returns as

{
    topLevel: {
        nextLevel: {
            ......
        }        
    }
}

So, in this context, toplevel would correspond to data, and nextLevel would represent user ... these abstract names of toplevel and nextLevel help explain why you encounter data.data with axios

The axios response structure is as follows

{
    data: {}, // server response
    status: 200, // response status
    statusText: 'OK', // response status text
    headers: {}, // response headers
    // etc - additional information not relevant here
}

Therefore, when using

axios.post(....)
.then(function (response) {
})

the equivalent of nextLevel would be response.data.topLevel.nextlevel

It's important to note that the server response is nested within the data property of the response variable - essentially two levels deep inside the response object

When utilizing fetch

fetch(....)
.then(response => response.json())
.then(response => .....)

(to avoid confusion, consider using a different variable name like result for the second .then)

In the scenario above, the FIRST instance of response looks like

{
    status: 200, // response status
    statusText: 'OK', // response status text
    headers: {}, // response headers
    body: // a readableStream of the response body
    json() {}, // method to parse the body as json
    // .... etc 
}

and the second response refers to the parsed JSON response from your server, hence, nextLevel can be accessed via response.topLevel.nextLevel

This response from the server is a property within (the second) response variable

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

Issue encountered: Inability to implement asynchronous functionality within a forEach loop while making an API request

When making a GET API call, the code looks like this router.get('/review', async (req, res) => { try { const entity = await Entity.find(); const entityId = []; Object.keys(entity).forEach((key) => { entityId.push(entity[ ...

Transforming a single object into multiple arrays using AngularJS

Just starting out with AngularJS and I've got some data that looks like this { day1: 0, day2: 0, day3: 0, day4: 2 } Is there a way to convert this data into arrays structured like below? [     ["day1": 0],     ["day2": 0],   ...

Tips for maintaining circular references when converting a JavaScript object to JSON string format

Currently, I am developing a filetree-like object that has a unique structure: var myObject = { 'name':'foo', 'contains': {'thisObject': myObject,'parentObject': /* the object that contains the cur ...

Encountering a problem in React when trying to install a color detection library

Hey there, I'm working on a Spotify-clone project where I want to detect the dominant color of an image and use it as the background color. Unfortunately, I've run into some errors while trying to integrate libraries like color-theif, node-vibran ...

JavaScript code snippet for detecting key presses of 3 specific arrow keys on the document

For this specific action, I must press and hold the left arrow key first, followed by the right arrow key, and then the up arrow key. However, it seems that the up arrow key is not being triggered as expected. It appears that there may be some limitations ...

Displaying content on a webpage using PHP, AJAX, and HTML

Looking to update my current form setup. I have a basic Form below: <form action="" method="POST"> <input type="button" value="Generate Numbers" onclick="on_callPhp1()"/> </form> Accompanied by this javascript code: <script type="te ...

html carousel not updating in popover

I've been attempting to create a popover with a bootstrap carousel, where the carousel items are dynamically generated and appended from a script. Despite my efforts, I have successfully displayed the carousel but struggle to append the items. I' ...

Utilize CSS properties to pass as arguments to a JavaScript function

Is there a way for me to make my CSS animation functions more efficient? I have similar functions for different properties like height, width, and left. Can I modify the function below to accept a CSS property argument instead of hardcoding height? Window ...

Differences in HTML animations can be seen when comparing Google Chrome to Microsoft Edge. Looking for a workaround for autoplay to ensure

My intro video animation is facing recording difficulties due to the autoplay policy in Google Chrome. It seems nearly impossible to capture it accurately. If only autoplay could function for an offline HTML file, my issue would be resolved. Unfortunately ...

I am looking to eliminate an object from an array based on the object's unique identifier

I am facing an issue with filtering an object based on the id in order to remove it from the array. The filter function I am using is not working as expected. My goal is to only remove the object that matches the provided id, while sending the remaining ...

Obtaining a result from a Promise in AngularJS

Here is a snippet of an Angular JS Service that I have: 'use strict'; app.factory('loggedService', ['$http', 'authService', 'customerService', function ($http, authService, customerService) { var out = ...

Retrieving Files from POST Request Body Using Node.js and Angular

Currently, I am developing a MEAN Stack application and facing an issue while handling a form that should allow users to upload a file upon submission. The process seems to work seamlessly on the client side; however, when I inspect the request body after ...

Encountering issues while trying to access 'weather' in NuxtJS API call due to undefined properties

I'm having an issue with the Open Weather API where I keep getting this error: Cannot read properties of undefined (reading 'weather'). Strangely, the error disappears when I move the v-list section to another page. Here is the code snippet ...

What is the best way to compare all the elements in an array to the entries in another object, while also storing the results of each comparison?

I am working with a JSON file that contains an array of 2 objects: `{ bg: 'a', o: 'c' }`, `{hg': 'a2', 'oo': 'c3'}`. My goal is to compare each object in the array with another object structured as fol ...

Issue with CSV download box not showing up on Rails version 2.3.11

I've encountered an issue while trying to export a csv file with some data. I am using ajax call to select rows from the view table (jqGrid) and export them in a csv format. However, after a successful ajax call, the filtered data is displaying as an ...

Guide to adding a line break following each set of 200 characters utilizing jQuery

I have a text input field where I need to enter some data. My requirement is to automatically add a line break after every 200 characters using JavaScript or jQuery. For example: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ...

How to eliminate duplicate items in an array and organize them in JavaScript

I am looking to eliminate any duplicate items within an array and organize them based on their frequency of occurrence, from most to least. ["57358e5dbd2f8b960aecfa8c", "573163a52abda310151e5791", "573163a52abda310151e5791", "573163a52abda310151e5791", "5 ...

Tips for storing form information using Flask and Vue.js

Currently, I am tackling a straightforward assignment that requires me to utilize tools with which I am not very familiar. In this task, I need to find a way to save the form data (preferably to a text file as the optimal solution) or at least serialize it ...

What is the proper way to invoke render functions using Vue 3 composition API?

During my time with Vue 2, I would typically call render() in this manner: export default { mounted(){ ... }, render(){ ... }, methods(){ ... } } Now that I'm exploring Vue 3 and the composition API, I ...

Guide to creating scroll-based animations for a Div element

I've been brainstorming ways to rotate a div as I scroll. My goal is to recreate the effect shown in this codepen. However, I'm struggling to implement scrolling functionality. What I envision is scrolling down causing the word Data to rotate in ...