VueJS is unable to access an array

Unable to access an array in Vue.js.

  console.log(this.ref_number_response[0]);

When I try to access the array, it shows undefined. I'm puzzled by this...

      data(){
        return{ 
           ref_number_response: [],
     }
},
methods:{
check_ref_number: function () {
             // sending axios request
             axios.get('/is_referenceNumber_free/'+this.ref_number)
             .then(response => this.ref_number_response.push({ 
                 info: response.data

              }));

        
console.log(this.ref_number_response[0]);
           Event.$emit('reference_added', this.ref_number_response);
             
         },
}
<div class="form-group">
        <label for="" class="col-sm-2 control-label">Ref Number</label>
        <div class="col-sm-10">
            <input v-model="ref_number" type="text" name="ref_number" class="form-control" id="" placeholder="Referent number" @blur="check_ref_number" required>
        </div>
    </div>

This is the current response I am receiving and I would like to avoid using v-for multiple times to get the actual diagnosis.

[ { "info": [ { "diagnosis": "St. post. trauma testis sin. Obs Ruptura testis sin." }, { "diagnosis": "diagnosi2" } ] } ]

Answer №1

The reason you see "undefined" is because the console.log statement is placed outside of the promise function. When you log ref_number_response, it's still an empty array and the first element in it will be undefined.

data(){
     return { 
           ref_number_response: [],
     };
},
methods: {
   check_ref_number() {
             // make axios request
             axios.get('/is_referenceNumber_free/'+this.ref_number)
             .then((response) => {
                  console.log(response.data);
                  this.ref_number_response = response.data;
                  console.log(this.ref_number_response); // now it's not empty
                  this.$emit('reference_added', this.ref_number_response);
             });
         },
}

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

When a function is transferred from a parent component to a child component's Input() property, losing context is a common issue

I have encountered an issue while passing a function from the parent component to the child component's Input() property. The problem arises when the parent's function is called within the child component, causing the this keyword to refer to th ...

"Mastering the art of data retrieval in ReactJS: A guide to utilizing hooks in functional

I'm in the process of working with nextjs and I'm attempting to implement a "functional component" utilizing "hooks" for fetching data using "axios". However, I'm encountering the following error message: "AxiosError: Request failed with sta ...

Adjust the number of documents in MeiliSearch to surpass the default limit of 20

Recently diving into MeiliSearch, I am in the process of setting up a basic demo. It bears resemblance to this official demonstration. I'm curious about adapting the default document limit of 20 within the application. How can this be accomplished? ...

Displaying dynamic SVG with AngularJS

Trying to generate an SVG based on data from the scope, but encountering issues with rendering - it comes out empty or displays 'NaN' for some unknown reason. Additionally, errors are popping up right after the render process: Is there a way to ...

Trigger a modal from one sibling Angular component to another

My application utilizes an Angular6 component architecture with the following components: <app-navbar></app-navbar> <app-dashboard></app-dashboard> The Dashboard component consists of: <app-meseros> </app-meseros> < ...

Is the input field not properly centered on the page?

Can someone explain why the input field is not aligning in the center? I am new to web development and need some assistance. <input type="text" id="search_bar" class="form-control" placeholder="Search" align="center"> In my CSS, I've ...

What is the best way to use jQuery to increment the number in an input field by a specific value?

My goal is to utilize jQuery to increment a number in an input field and then display the updated value in the same input field. The specific id of this input field is "total". Here's my attempt so far: function addBag(){ var bagprice = 79.99; ...

Is there a way I can obtain the code for a message box?

When I refer to a message box, I am talking about a container that gives users the ability to input their text and access different features like BOLD, ITALIC, color, justify, etc., in order to customize their message's appearance! (Think of it as the ...

What is the proper location to place the .env file in a Vue3 CLI project?

I have recently completed a project using Vue3-CLI. In order to manage environment variables, I decided to utilize both the .env and .env.development files in my project structure. After setting up these files, however, I noticed that my variables such a ...

What is the best way to ensure that all input is consistently capitalized in vue.js?

As I work on a form with vue.js, I face the need to have inputs in vue that are always capitalized. My initial thought was to use the CSS property text-transform: uppercase; and then transform the data before sending it using data.someData.toUpperCase() ...

Ways to utilize JavaScript to identify if a flash is launching in a separate tab

On my website, I have embedded a third-party flash player using an iframe. Whenever a user clicks on a specific area within the flash player, a new tab is opened in the browser. I am trying to track the frequency of this occurrence. However, I have encoun ...

Creating new Vue.js templates within Laravel using the bundled App.js package

Once upon a time, I hired a developer to add new features to my app without having much knowledge about Vue.js. Unfortunately, the developer only updated the app.js file and not the necessary vue files. Fast forward a year later, when we wanted to add more ...

What is the best way to update the state of object.item[n] that is nested within an array, which in turn is nested within

A unique data structure is set up in the following way: const library = [ { procedureName:'Build Foundations', id:1, tasks:[ { taskName:'dig at least 1m deep', isCompleted:false, procedureId:1 }, ...

Export a function within a function to be used in another file in Javascript

I'm encountering an issue regarding exporting a function within a function to another function in a separate file, while working with the React framework. The code snippet provided below is not functioning as expected, despite my attempts to troubles ...

Encasing extracted content in <p> tags

On my Wordpress Site, I have extracted images and text separately to use in different sections of my single.php file. Utilizing HTML within the Bootstrap 3 framework: <div class="row"> <div class="col-md-12"> <?php ...

Modifying JavaScript object values using the Object() constructor

My background is in Groovy, which has similar syntax to JavaScript. In Groovy, I can easily copy values from one map to another like this: def myMap1 = {}; def myMap2 = {}; myMap1["key1"] = "value1"; myMap1["key2"] = "value2"; myMap1["key3"] = "value3"; ...

Discovering parent elements far up the DOM hierarchy using jQuery

I'm a bit confused about how to locate an element that is a parent element further up the tree. $('.btn-action').hover( function(){ $(this).find('.product-card').addClass('animated bounce'); }, function(){ ...

Warning: npm is resolving peer dependency conflicts during the installation process

Upon running npm install for my React application, I encountered the following warnings in the logs. Despite that, the npm installation completed successfully and the dependencies were added under node_modules. My app even starts up without any issues. I ...

How do I declare the links in my navigation drawer?

I have successfully implemented a navigation drawer with dropdown menus. However, I'm struggling to figure out how to declare the routes so that clicking on the navigation names redirects me to the desired route. Can you guide me on how to properly de ...

Encountering an error in Jest with TypeScript (Backend - Node/Express) that reads "Cannot use import statement outside a module

Currently, I am in the process of developing Jest tests for a Node/Express TypeScript backend. Recently, I came across the concept of global test setup which I am integrating to streamline the usage of variables and function calls that are repeated in all ...