Unable to transfer the information from axios to the data return variable in Vue.js

Having a problem with my Vue template below. I used axios to fetch data but couldn't save it in the this.sub_brand variable. The console.log(this.sub_brand) only works within axios. Here is the complete code:

<template>
<div>
    <div class="row" >
        <div class="col-md-4 pt-5 pl-5">
            <div class="product">
                <div class="product__images">
                    <img
                        src="http://127.0.0.1:8000/images/gsm.jpg"
                        alt="google pixel 6"
                        class="product__main-image"
                        id="main-image"
                    />

                    <div class="product__slider-wrap">
                        <div class="product__slider">
                            <img
                                src="http://127.0.0.1:8000/images/gsm.jpg"
                                alt="google pixel 6"
                                class="product__image product__image--active"
                            />
                            <img
                                src="http://127.0.0.1:8000/images/gsm.jpg"
                                alt="google pixel 6"
                                class="product__image"
                            />
                            <img
                                src="http://127.0.0.1:8000/images/gsm.jpg"
                                alt="google pixel 6"
                                class="product__image"
                            />
                            <img
                                src="http://127.0.0.1:8000/images/gsm.jpg"
                                alt="google pixel 6"
                                class="product__image"
                            />
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-5 pt-5 pr-5">
            <h4>{{sub_brand}}</h4>
            <!-- <input type="text" class="form-control" name="" id="" v-model="sub_brand"> -->
            <h5>Star</h5>
            <div class="bg-light mt-4" style="padding: 10px 0px">
                <h2 class="pl-4 pt-3">RM869.00</h2>
            </div>
            <div class="mt-4">
                <h3>Variation</h3>
            </div>
            <div class="bg-light mt-4" style="padding: 10px 0px">
                <h5 class="pl-4">Quantity: </h5>
                <input type="number" class="form-control pl-4" placeholder="0" style="width: 12%; margin-left: 4%" min="0">
            </div>
            <div class="row mt-5">
                <button class="btn btn-secondary ml-3">Add to Cart</button>
                <button class="btn btn-primary ml-3">Buy Now</button>
            </div>
            <hr class="mt-5">
        </div>
        <div class="col-md-3 bg-light">
            <div class="pl-5">
                <h3><strong>Samsung</strong></h3>
            </div>
            <div class="pl-5 custom_pan">
                <a href="">Chat</a>
                <a href="" class="pl-3">Video Chat</a>
                <a href="" class="pl-3">View</a>
            </div>
            <hr>
            <div class="pl-5 mt-4 pr-4">
                <strong>Shipping Details</strong>
                <p style="color: #D1D3D4">2A, Changkat Duta Kiara, Mont Kiara, 50480 Kuala Lumpur, Willayah Persekutuan Kuala Lumpur</p>
                <strong>From: China Logistic, Shankal</strong>
                <br><br>
                <strong>To: Kuala Lumpur, Willayah Persekutuan</strong>
                <br><br>
                <strong>Shipping Fee: RM8.00</strong>
            </div>
            <hr>
            <div class="pl-5 mt-5">
                <h5>Authentic</h5>
                <br>
                <h5>15 Days Return</h5>
                <br>
                <h5>Free Shipping</h5>
            </div>
            <br><br>
        </div>
    </div>
    <div class="row bg-light">
        <div class="card">
            <div class="card-header">
                <h4>Product Description</h4>
            </div>
            <div class="card-body">
                Samsung
            </div>
        </div>
    </div>
    <div class="row bg-light">
        <div class="card">
            <div class="card-header">
                <h4>Review</h4>
            </div>
            <div class="card-body">
                Samsung
            </div>
        </div>
    </div>
    <div class="row bg-light">
        <div class="card">
            <div class="card-header">
                <h4>You may also like other products from the same merchant</h4>
            </div>
            <div class="card-body">
                Samsung
            </div>
        </div>
    </div>
    <div class="row bg-light">
        <br><br>
    </div>
</div>
</template>
<script>
import axios from 'axios';
    export default {
        mounted() {
                // console.log('Component mounted.');
                this.fetchProduct(); 
        },
        data() {
            return{
                single_product: [],
                sub_brand: "",
                product_id: 6,
            }
        },
        methods: {
            fetchProduct(){
                axios.get('https://admin.globalshopping-mall.site/api/single_sub_brand_detail/'+ this.product_id)
                .then(res => {
                    this.single_product = res.data.data[0];
                    this.sub_brand = res.data.data[0].GUID;
                }).catch(err => {console.log(err);});
                
            },
            
        },
        
    }

    
</script>

<style>
    .card{
        margin-top: 2%;
        margin-left: 4%;
        background-color: white;
        width: 71%;
        /* height: 30%; */
    }
    .card-header{
        background-color: white
    }

    .product {
        width: 100%;
        height: 68%;
    }

    .product__images {
        width: 100%;
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
    }

    .product__main-image {
        max-width: 500px;
        max-height: 600px;
        object-fit: cover;
        cursor: pointer;
        border: 1px solid #070707;
    }

    .product__slider-wrap {
        max-width: 500px;
        min-height: 100px;
        display: flex;
        align-items: center;
    }

    .product__slider {
        width: 98%;
        display: flex;
        flex-wrap: nowrap;
        overflow-x: auto;
        padding-left: 2%;
    }

    .product__image {
        max-width: 180px;
        max-height: 100px;
        object-fit: cover;
        cursor: pointer;
        opacity: 0.5;
        margin: 0.25rem;
        border: 1px solid #070707;
    }

    .product__image:first-child {
        margin-left: 0;
    }

    .product__image:last-child {
        margin-right: 0;
    }

    .product__image:hover {
        opacity: 1;
    }

    .product__image--active {
        opacity: 1;
    }

    .product__slider::-webkit-scrollbar {
        height: 10px;
    
    }

    .product__slider::-webkit-scrollbar-thumb {
        background-color: #D1AD33;
        border-radius: 50px;
    
    }
</style>

Answer №1

It seems like the issue lies in how your context this. is functioning within axios, as it only works with the context of axios itself. If you wish to access the context this. of the Vue component, you'll need to retrieve the data from axios externally. To achieve this, utilizing async/await in your vue method fetchProduct is necessary. Below is an example:

methods: {
    async fetchProduct() {
      let result = await axios.get("https://admin.globalshopping-mall.site/api/single_sub_brand_detail/" +this.product_id)
        .then((res) => {
          return res.data.data[0];
        })
        .catch((err) => {console.log(err);});

      this.single_product = result;
      this.sub_brand = result.GUID;
    },
  },

Alternatively, you can store your context this in a variable before calling axios and then use that variable within the axios function. Here's an example:

methods: {
    fetchProduct() {
      let _this = this;
      axios.get("https://admin.globalshopping-mall.site/api/single_sub_brand_detail/" + this.product_id)
        .then((res) => {
          _this.single_product = res.data.data[0];
          _this.sub_brand = res.data.data[0].GUID;
        })
        .catch((err) => {console.log(err);});
      console.log(this);
    },
  },

Answer №2

Main cause : Due to the asynchronous nature of axios API calls, there is a discrepancy in timing with other synchronous code execution. This results in logging this.sub_brand synchronously before the axios call completion.

Solution : To access the API response immediately after making a call, utilize async/await functionality for simplified promise handling.

  • async ensures a function returns a Promise
  • await allows a function to pause until a Promise resolves

Check out this Live Demo for implementation:

methods: {
    async fetchProduct(){
        const res = await axios.get('https://admin.globalshopping-mall.site/api/single_sub_brand_detail/'+ this.product_id)
        .then(res => {
          return res.data.data[0];
        }).catch(err => {console.log(err);});            
    }
    this.single_product = res;
    this.sub_brand = res.GUID;         
}

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

Closing a Vue modal with a button

Utilizing the bootstrap-vue framework for my modal, I encountered an issue. Upon clicking the button labeled OPEN MODAL, the modal opens with footer buttons OK and CANCEL, which work as expected to close the modal as per bootstrap-vue's default behavi ...

The ongoing saga of `npm run dev` seems to have no end in sight

I've been attempting to integrate Vue into my Laravel project, and I've followed all the necessary steps: Installed Laravel/UI using composer require laravel/ui Ran php artisan ui vue Included the in my main layout file app.blade.php Ran npm ru ...

Tips for overcoming indentation issues using ESLint?

Ever since I started using Vue 3 with ESlint, I've been encountering a new problem. Whenever I try to run my code, I am bombarded with numerous errors like: --fix option.

I'm looking for ways to disable this troublesome feature of ESlint. H ...

A more concise approach to crafting ajax requests

Lately, I've been immersed in building various web applications using php, mysql, jquery, and bootstrap. Now, I'm faced with a common issue - how to streamline my ajax queries for posting data? Writing code that is not only functional but also a ...

Prevent user input in Vue.js until the value has been modified

Need help handling initial input values: <input type="text" v-model="name" ref="input" /> <button type="submit" :disabled="$refs.input.defaultValue == $refs.input.value">Submit</button> Encountering an error with the disabled binding: C ...

Attempting to download an image through an axios fetch call

There is an issue I am facing while trying to retrieve an image from the website www.thispersondoesnotexit.com. function getImage() { axios({ method: 'get', url: 'https://www.thispersondoesnotexist.com/image' }) ...

Is it possible to transition my Vue.js web application to NativeScript-Vue?

Hello, I have a quick question for you. I currently have a web project developed in Vuejs and I am wondering if there is a way to convert it or mirror it to NativeScript-Vue somehow. Thank you and warm regards! ...

JavaScript - The progression of a virtual pet even when the user is offline

Currently, I am utilizing VueJS and MongoDB to develop an interactive virtual pet. Our approach involves storing user data in localStorage for easy access and retrieval. I'm exploring the concept of allowing the virtual pet to evolve autonomously (s ...

What is the method for accessing a map that has been set in a separate component?

My current setup involves utilizing a Leaflet map with vue2leaflet. The process I follow is quite standard: I import a list of places from a REST Api in the app store (vuex) Following that, during map initialization, the markers are created using the in ...

Vue.js: Issue with dynamically calculating class property

I am attempting to create a computed class in vue.js 2.0 using the following syntax: <li :class="'str1' calcStarClass(1, p.rtg)"> </li> In my methods section, I have the foll ...

What is the most effective method for daily column reset with a large user base?

While working on my current project in Laravel, I've come across the need to implement a feature that requires a column reset for all users every day. With potentially hundreds or thousands of users in this project, I'm concerned about potential ...

Execute a function as soon as an AJAX request is made

Once an AJAX call is initiated with Axios, a message saying "Request for execution sent" needs to be displayed before the response is received. axios .post('executeTask', { id, status, name }) .then(response => { }) .ca ...

When I download the image/file, I am receiving encoded data

I have successfully implemented a proxy in my NestJs Application to work around the CORS restrictions. The service endpoint is - https://api.niftyuat.com/cors?cd=https://google.com By using this endpoint, I am able to retrieve the content of the Google ...

Mastering the use of v-if and v-else in Vue JS for <td> table elements

After exhausting my search efforts without finding a solution, I am turning to this platform for clarification on how to correctly implement the v-if and v-else directives within <td> elements in an HTML table in Vue. //assuming that the value of th ...

Configuring properties of a child component in VueJS

Currently, I'm exploring the method of utilizing a Vue template as a Kendo UI template in their components. However, I found that there's a lack of clarity on how to provide properties to components rendered using this approach instead of directl ...

Laravel's Vue component is experiencing issues with loading Axios response data

Hey everyone, I hope you're all doing well! I'm facing a bit of an issue with passing data from an axios response to the data property. The data is successfully fetched from the database and displayed in the console, but when I try to display it ...

Mastering data extraction from JSON using React JS (with Axios)

Being new to ReactJS and axios, I am facing a challenge. I need to iterate through JSON data and extract values where the key is a number (e.g. 0, 1, 2...). However, I am unsure how to implement this in my code since the server provides dynamic JSON data ...

Tips for implementing a shape divider in vuetify.js

Currently, I am incorporating the vuetify library into my project and attempting to include a shape divider similar to the one displayed in the image below. Unfortunately, I have been unsuccessful in achieving this desired effect. https://i.stack.imgur.c ...

Guide to building a personalized autocomplete feature in vue js

Presently, I am using the buefy autocomplete feature, but it is causing a few problems. In the DepartmentDetail.vue file <template slot-scope="props"> <div class="container is-fluid"> <b-loading :is-full-page=" ...

What is the best way to adjust the dimensions of a textfield in Vuetify by altering its width and height?

Is there a way to adjust both the width and height of the <v-text-field>tag? I attempted to modify it using .css, but it seems to only affect certain parameters, leaving large white spaces on my page. This is the method I have tried so far: <te ...