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

Ways to have MongoDB present nested JSON data as an array?

I recently came across some interesting data: { "_id" : ObjectId("5461e16ee7caf96f8f3584a2"), "num_marcacao" : "100", "sexo" : "Fêmea", "idade" : "20", "bigdata" : { "abortos" : [ { "data_aborto" : ...

Stopping a velocity.js animation once it has completed: is it possible?

For the pulsating effect I'm creating using velocity.js as a fallback for IE9, refer to box2 for CSS animation. If the mouse leaves the box before the animation is complete (wait until pulse expands and then move out), the pulsating element remains vi ...

I am receiving a 401 error when attempting to verify the token following a successful login

I've been working on a small project utilizing VueJS, Vue Router, and Laravel for the backend. Despite several attempts, I haven't been successful in implementing navigation guards. My login component is functioning properly. Here's my log ...

Ways to show dropdown menu link exclusively on mobile browsers and not on desktop browsers

<li class="megamenu-content"> <div class="megamenu-content-wrapper clearfix"> <ul class="col-lg-3 col-sm-3 col-md-3 "> <li class="cat-header">DISPLAY MEMBERS</li> ...

Using the factory pattern in a Node.js (Express) application

As I delved into the realm of design patterns, I found myself drawn to the factory pattern. However, as I perused through code written by others, I noticed that this particular pattern wasn't as prevalent, especially in newer stacks. Take for example ...

Give GetElementsByClassName a shot

Hey, have you tried using js ref_doc_getelementsbyClassName? "I keep getting the error message 'Uncaught TypeError: Cannot set property 'value' of null' " Check out this HTML code snippet: <input type="text" cla ...

Eliminate the navigation bar option from a website template

Is there a way to permanently eliminate the menu button in this theme? Any guidance would be appreciated. Here's the link to the theme: https://github.com/vvalchev/creative-theme-jekyll-new ...

Error encountered while attempting to retrieve an environment variable: Invalid token found

I am currently facing an issue while trying to add an environment variable inside the .env file in my Nuxt project. The version of Nuxt.js I am using is 2.15.3 Below is a snippet from my nuxt.config.js: export default { publicRuntimeConfig: { baseU ...

Avoiding duplicate clicks in Onsen UI Navigator.Avoid duplicate clicks in

When a user clicks on an item in my list, they are taken to a details page. However, if the user clicks too quickly, two click events may be fired, leading them to navigate to two different pages consecutively. Is there a way to prevent this issue? Can we ...

"Optimize Magellan Sidebar for Mobile Devices by Relocating it to the Bottom of the Page

After spending a week working with Foundation 5 framework, I'm curious if there is a straightforward way to make my magellan sidebar shift to the bottom of the page when viewed on mobile or tablets. <div data-magellan-expedition="fixed"> <di ...

Scroll positioning determines the height of an entity

Here's a code snippet I'm working with: HTML: <div id="wrap"> <div id="column"></div> </div> CSS: #wrap { display: block; height: 2000px; width: 400px } #column { display: block; height: 20px; ...

Unable to locate the node module within the Rails stimulus controller

I'm facing an issue with integrating my own npm package into a Rails application that I have developed. It's unclear whether the problem lies in the creation of the node package or within the rails app itself. The package in question is fairly ...

Error: Unable to locate sportsRecord due to missing function

updated answer1: Greetings, I have updated the question with some detailed records and console logs for better understanding. sportsRecord = { playerTigers:[ {TigerNo: 237, TigerName: "Bird Bay Area", TigerkGroupNo: 1, isDefault: true ...

When using Jquery, input can be appended on the last child element when a key

I am new to JavaScript and want to enhance my page's functionality using jQuery. Here is my current HTML: <div class="input_fields_wrap"> <div><ul class="inputList"></ul></div> </div> My goal ...

Is JavaScript's setTimeout 0 feature delaying the rendering of the page?

Based on information from this StackOverflow post The process of changing the DOM occurs synchronously, while rendering the DOM actually takes place after the JavaScript stack has cleared. Furthermore, according to this document from Google, a screen r ...

Altering the hue of various stroke patterns

I've encountered an issue where I want to create skill bars that display my skills in percentages. Luckily, I found a great code that allows me to do this. Although I would prefer to do it myself, I haven't come across a good tutorial that teache ...

The disappearance of HTML DOM nodes event

When I relocate certain DOM nodes from one context to another, some of the child nodes end up losing their event listeners. HTML <div><lots of nested nodes .../><div> <div> <div> <div#newNode></div> < ...

Ensuring a correct dismount of a React component

Apologies for the lack of specificity in the title of this inquiry. Upon executing the code snippet below, I encountered the ensuing warning: Warning: setState(...): Can only update a mounted or mounting component. This typically indicates that you call ...

Are Viewmodel contents empty after ajax request?

Currently working on an ASP.NET MVC application, I am in the process of developing a search page that showcases both the search box and the table of results simultaneously. To achieve this functionality, I have utilized Partial Views along with AJAX/JSON c ...

Issue with sending array as parameter in ajax call in Laravel

I am currently encountering an issue while attempting to pass an array through an AJAX request. <input type="text" name="item_name[]"> <input type="text" name="address"> $(document).on('click', '#save_info', function () { ...