Having difficulty accessing a public array item within chained AXIO transactions in VUE

I am currently facing an issue with a chained AXIOS call that is triggered from an array. The challenge I am encountering is ensuring that the second call completes before the first one initiates another API request, which seems to be working fine so far. However, my main problem lies in the fact that I am unable to reference anything from within the response of the second chain. I need to update either the calling array (arr), a public array this.excelData.results, or even a deep copy of the original array. Each time I try to access the data, I receive the following error message:

 TypeError: Cannot read property 'ORCID' of undefined at eval (webpack- 
    internal:///./node_modules/cache-loader/dist/cjs.js?!./node_modules/babel- 
     loader/lib/index.js!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue- 
    loader/lib/index.js?!./src/views/examples/ExcelWorksheet.vue?vue&type=script&lang=js&:410:49) at 
    NodeList.forEach (<anonymous>) at eval (webpack-internal:///./node_modules/cache- 
   loader/dist/cjs.js?!./node_modules/babel-loader/lib/index.js!./node_modules/cache- 
   loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/views/examples/ExcelWorksheet.vue? 
   vue&type=script&lang=js&:381:28) at NodeList.forEach (<anonymous>) at eval (webpack- 
    internal:///./node_modules/cache-loader/dist/cjs.js?!./node_modules/babel- 
    loader/lib/index.js!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue- 
    loader/lib/index.js?!./src/views/examples/ExcelWorksheet.vue?vue&type=script&lang=js&:378:33)

I have attempted using 'this' and 'self', but nothing appears to resolve the issue. While debugging in a browser, all elements of the array are visible, yet I am unable to retrieve or manipulate them in code. Is there a specific procedure I should follow to access the data from the second AXIOS call within the original array?


lookUpORCID(){
   this.pubmedArticles=[];
   this.makeRequestsFromArray(this.excelData.results);
},
makeRequestsFromArray(arr) {

   var self = this
   let index = 0;
   function request() {
      let authorName = arr[index]["Last_Name"]

      let linkGetIdList = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?';
      linkGetIdList += 'tool=biosketch&db=pubmed&retmode=json&retmax=200&';
      linkGetIdList += 'term=' + authorName +'[AU] ';
      
      return axios.get(linkGetIdList).then((res) => { 
         index++;
         let idlist = res.data.esearchresult.idlist
         const passID = idlist.join(',')
         if (idlist.length > 0) {  
            var getXmlLink = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?';
            getXmlLink += 'db=pubmed&retmode=xml&id=${passID}';         
            return axios.get(getXmlLink).then((response) => {
               // parse document
               const parser = new DOMParser()
               const xmlDoc = parser.parseFromString(response.data, 'text/xml') // Get ALL XML content
              // Do Stuff

              **This is the spot that I need to change value in array**
              let xyz = arr[index]["ORCID"]

              return request(); 
           }) 
         }

         if (index >= arr.length) {
            return 'done'
         }
      });

  }
  return request();
}

}

Answer №1

If you can access the value of the variable arr, then you would not encounter the error message:

cannot read property index of undefined
.

The reason for this error is that you have increased the value of the variable index after the initial request, and at the incremented position, the variable arr holds the value undefined. As a result, the error states:

Cannot read property 'ORCID' of undefined
.

To confirm the above, consider using console.log(arr[index]) before executing let xyz = arr[index]["ORCID"].

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

Manipulating the vueObject.dataItem variable in Vue JS directly affects the underlying Vue data item

I’ve encountered a troublesome behavior in my projects. Here is a simplified explanation of the issue at hand. I am eager to understand why this occurs and how I can prevent it. I have included Vue in the head section of my website: <script src="http ...

Adding a characteristic to every item in an array of objects

Currently, I am utilizing Node.js along with Mongoose to interact with a MongoDB database and retrieve an array of objects from a specific collection. However, my aim is to add an additional property to each of these retrieved objects. Below, you can see t ...

``tips for concealing the sidebar on a Vue.js application`

Welcome everyone, I am a newcomer to Vue and have decided to use a CoreUI admin panel to work on some cool Vue projects. However, I have hit a roadblock while working on the nav.js file. export default { items: [ { ...

Is It Best to Override Behavior in a Directive?

Having two directives that display lists of documents, one for user-favorited documents and the other for user-pinned documents. The criteria for displaying these documents depend on the values of "pinned" and "favorite" within each document object: docum ...

Running concurrently, the JavaScript if and else statements execute together

I am looking to create a clickable link that changes the background color when clicked. If the same link is clicked again, I want the background to return to its original state. Here is my current script: <div style="background: transparent;" onclick=" ...

Turning a Static Website Dynamic with Faceapp.js

After installing node_modules and adding faceapp.js as a dependency, I attempted to use it but unfortunately encountered some issues. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta ...

Strange Reselect selector actions

It seems like my selector function is only triggered when one of the arguments changes, not both. Here's the selector I'm using to retrieve transactions from the state and apply two filters to them: export const getFilteredTransactionsSelector ...

Discovering alterations in current value rather than simply OnChange using nuxt and vuetify

Due to export default { name: "Details", async asyncData({ redirect, params, store }) { if ( !store I am providing multiple values, including return { camera: c, thumbnail_url: thumbnail_url, The camera value is being populated ...

Tips on sending data with a unique identifier to the backend through a route parameter

Can anyone help me figure out how to send a message to a specific backend route parameter while passing the current ID? I'm not sure how to inform the system about this ID. Here's the Vuex action: postMessage({commit}, payload, id) { axios.pos ...

Maximizing Particle Performance Using JavaScript

I am experimenting with creating particles in JavaScript for the first time, and I'm unsure if the code below is optimized. When I generate 100 particles on the screen, there isn't much of an FPS drop noticeable. However, when multiple clicks o ...

Managing the storage of refresh and authorization tokens on the client side: where should they be kept?

My backend is powered by Laravel and the frontend uses Vue. Users authenticate by calling my Laravel API to get an Auth token and a refresh token. The Auth token expires after 2 minutes, while the refresh token lasts longer. Storing the refresh token in l ...

What is the best way to import a JSON file in VueJs without the need for compilation?

I am facing an issue while developing a VueJs application. I have a JSON file containing an array of objects, and when displaying based on search criteria, it results in generating a very large app.js file, causing the application to boot slowly. Currentl ...

Limiting Velocity in a Two-Dimensional Spacecraft

Like many others diving into the world of programming, I decided to challenge myself with a spaceship game project. At this point, I have successfully incorporated parallax stars and other essential features expected in a space-themed game. The spacecraft ...

NPM Error: 403 Access Denied - Attempting to PUT http://registry.npmjs.org/[package-name] has been Forbidden

Struggling to create a brand new npm vue component library. I've followed all the necessary steps but now I'm stuck at the point of running `npm publish`. After spending over an hour searching on Google, I still can't find a solution for th ...

Learn how to incorporate a custom event listener for Vuetify's v-select component by utilizing directives

My issue involves a v-select element <v-select :items="[1, 2, 3]" label="Some items" v-mydirective ></v-select> Along with the following directive: Vue.directive("mydirective", { bind: function(el, binding) { ...

Passing a variable to a component attribute in Vue.js

Is there a way to pass variables to a component in Vue.js without using props? Is this even possible? Take a look at app.js below: import PlayingField from '../app/components/PlayingField' import GameConfig from '../../gameConfig' ne ...

When a tooltip inside a button is clicked, the hover effect is passing through to the surrounding parent element

I am facing an issue with a nested tooltip within a button. The problem arises when I try to click on the 'read more' link inside the tooltip popup, intending to go to an article. However, instead of redirecting me to the article, clicking on the ...

Ways to Increase jQuery Element ID

I have several instances of jPlayer (a jQuery audio player) set up: jPlayer1, jPlayer2, jPlayer3, jPlayer4. Each one is initialized and preloaded with audio files. The following function will loop through an existing array and attach a method to play the ...

The binding style in vue.js using the ternary operator is throwing an error: Unexpected token ']'

partNav = Vue.component('part-nav', { data: navItems: [ { subItems: [ {...} {....} ] } {...} # another object in navItems array ] template: ' <div v-for="(navIte ...

Express.js response.json method can be used to render both HTML and JSON content in the

I have a router that is sending JSON data to the client as shown below: router.get('/', function(req, res, next) { UserModel.selectAllUsers(function(err, vals){ if(err){ console.log(err); } res.json({d: v ...