Unable to iterate over an array within a single file Vue component

I created a vue.js app utilizing single file components. In the data section, I initialized an empty array like this:

data: function () {
  return {
    teamKeys: []
  }
},

Next, I populate this array by pushing values into it within one of my methods:

fetchTeams (token) {
  var this_ = this
  var url = 'myapiserver.com/teams'
  this.axios.get(url, {
    params: {
      accessToken: token
    }
  })
    .then(function (response) {
      var teams = response.data.teams[0].teams
      teams.forEach(function (t) {
        this_.teamKeys.push(String(t.team_key))
      })
    })
    .catch(function (error) {
      console.log(error)
    })
},

(updated with actual fetchTeams method) Later on, in another method, I try to iterate over the array using forEach.

fetchRosters (token) {
  var teamKeys = this.teamKeys
  teamKeys.forEach(function (key) {
    console.log(key)
    // perform actions here
  })
}

These methods are consecutively called within the mounted lifecycle hook:

mounted () {
    this.$nextTick(() => {
      var accessToken = this.$route.query.accessToken
      this.fetchTeams(accessToken)
      this.fetchRosters(accessToken)
    })
  }

The loop using forEach doesn't seem to work as expected; it appears that the array is being treated as empty since the code inside the loop never executes. Additionally, if I log the array just before calling forEach:

console.log(this.teamKeys)
console.log(JSON.stringify(this.teamKeys))

the second output displays an empty [], while the first output in the console looks like this:

Array(2)
0: "371.l.215756.t.1"
1: "371.l.621475.t.2"
length: 2
__ob__: Observer {value: Array(2), dep: Dep, vmCount: 0}
__proto__: Array

I'm convinced there's a simple mistake I'm making. Perhaps I overlooked something in creating the array? Or maybe my understanding of arrays needs revision?

Answer №1

retrieveTeams (authToken) {
  var self = this
  var apiURL = 'myapiwebsite.com/teams'
  this.fetch(apiURL, {
    params: {
      authToken: authToken
    }
  })
    .then(function (res) {
      var teamsData = res.data.teams[0].teams
      teamsData.forEach(function (team) {
        self.teamKeys.push(String(team.team_key))
      })
      //this will trigger the next step
      self.retrieveRosters(authToken)
    })
    .catch(function (err) {
      console.log(err)
    })
},

Answer №2

It appears that you forgot to include the closing parentheses ')' in the third snippet

Answer №3

retrieveTeams (token) {
  var current = this
  var apiUrl = 'myapiserver.com/teams'
  return this.axios.get(apiUrl, {
    params: {
      accessToken: token
    }
  })
}

mounted () {
  this.$nextTick(() => {
    var accessToken = this.$route.query.accessToken
    this
      .retrieveTeams(accessToken)
      .then(function (response) {
        var teamsData = response.data.teams[0].teams
        teamsData.forEach(function (team) {
          current.teamKeys.push(String(team.team_key))
        })
        current.fetchRosters(accessToken)    
      })
      .catch(function (error) {
        console.log(error)
      })
  })
}

Alternatively:

fetchTeamsData (url, token) {
  return this.axios.get(url, {
    params: {
      accessToken: token
    }
  })
}

mounted () {
  this.$nextTick(async _ => {
    var accessToken = this.$route.query.accessToken
    var response = await this.fetchTeamsData('myapiserver.com/teams', accessToken)
    var teamsData = response.data.teams[0].teams
    teamsData.forEach(team => {
      this.teamKeys.push(String(team.team_key))
    })
    this.fetchRosters(accessToken)
  })
}

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

What is the best way to conceal the header on a 404 error page?

<HeaderContainer> <Switch> <Route exact path='/counters' component={ParentCounterContainer}/> <Route exact path='/about' component={AboutContainer} /> <Route exact path='/' component={H ...

AngularJS is experiencing issues with the sorting filter 'orderBy'

I am experiencing an issue with sorting a table list that has three columns. I have implemented the ability to sort all columns in ascending and descending order. However, when I click on the -Tag to initiate the sorting process, I encounter the following ...

The completion action is never carried out

I am currently facing an issue with one of my JavaScript functions. I have several $.ajax calls throughout my webpage followed by .done(), and they all seem to be functioning properly, except for one. Can anyone identify what could be causing the error? m ...

Show a Pair of Images Upon Submission Utilizing Ajax

Imagine having two separate div containers displayed as shown below: What I achieved was clicking the submit button would upload the image to the designated area. However, my goal is for a single click on the button to load the image in both containers. ...

Autofill with JavaScript - Dynamic Form Population

Looking to create a form-based HTML page. The objective is to have the second input box automatically populate based on the user's input in the first input box. I've gone through various guides and tried to implement this script, but it doesn&ap ...

What is the best way to determine which DOM element triggered a click event?

I currently have a few Card components from material UI, each containing an EDIT button with a corresponding handler. These cards are dynamically added using Map traversal (for this example, I have hard coded two of them). My challenge now is trying to ma ...

Showing events from MySQL database on Vue.js Fullcalendar

I am trying to fetch events from my MySQL database and pass them to my Vue component to be displayed on the FullCalendar. However, the event array is being populated with a full HTML document. Below is my EventController: public function getEvents() { ...

Accessing a precise div element in a webpage

Currently, I am utilizing Vue.js and Nuxt for my web development. One issue I am facing is related to anchors. Specifically, when I navigate to mysite.com/page1#section1, I want the page to scroll to section1. In my code, I have the following snippet: < ...

The response from the Whatsapp-web-js API can be delayed

As I work on creating an API to retrieve groupChat IDs using the express framework and whatsapp-web-js library, I've encountered an issue. The initial request to the endpoint after starting the server yields a response within 31 seconds, but subsequen ...

Determine if a webpage forwards to a new link with the help of phantomjs, flagging any issues exclusively for designated websites

As a beginner in frontend development, I have a question that may seem simple. Please be patient with me. var page = require('webpage').create(), system = require('system'); if (system.args.length === 1) { console.log('Usage: ...

Error in AWS Lambda: JSON parsing error due to unexpected token 't' at position 6

I'm currently working on a basic lambda function that utilizes a post request to insert data into DynamoDB. However, every time I deploy the lambda function and test it using Postman, I keep encountering a 502 Bad Gateway error. To troubleshoot this ...

Apollo GraphQL has initiated the detection of a new subscription

My approach involves utilizing graphql-ws for subscribing to GraphQL events. I rely on the Observable interface to listen to these events. Although I can use the error callback to identify when a subscription fails to start, it is challenging to determine ...

Collaborative gaming experience with three.js and socket.io

I created a basic scene in three.js that I find really fun to interact with. However, I wanted to enhance it by adding multiplayer functionality through a socket.io server. To achieve this, I prompt the user for their username: var username = prompt("what ...

When attempting to browse for image files, Postman fails to display images

While trying to upload image files through Postman, I encountered an issue where the browser did not display any image files. It's important to note that I am using Ubuntu as my operating system. When I clicked on "select files," the option appeared ...

Generate random div elements and insert them dynamically into a fixed-sized container using AngularJS. The number of div elements created can range anywhere from 0 to

Within a div of fixed size, dynamically generated div elements are displayed using ng-repeat. The inner divs should adjust their size to accommodate the number of child divs present - for example, if only one div is present, it should take up 100% of the s ...

Using Sequelize to Include Model Without Specifying Table Name

I am new to Sequelize I am facing an issue with "Nested Eager Loading" I have 2 tables with a one-to-many relationship Comment Table User Table This is the code I am using for the query Comment.findAll({ include: [User] }) The result I got was ...

Importing Vue and Vuex modules from separate files

Recently, I encountered an uncommon issue. I decided to keep my main.js and store.js files separate in a Vue project. In the store.js file, I imported Vuex, set up a new vuex store, and exported it. However, when importing this file into main.js and settin ...

Issue with ng-disabled not functioning properly for href tag within list item

Is there a way to prevent clicking on the <a> tag within a list item in a UI list so that the associated <div> is not displayed when clicked (excluding the last list item)? I have attempted using ng-disabled directly on the list item attribute ...

The caption below the image is not functioning correctly when hovering over it

I'm having trouble getting the text to appear correctly underneath the image. Whenever I hover over the image, the text seems to overlap it. I am sure there is a simple solution to this issue, but I can't seem to figure it out. Removing the inlin ...

What is the best way to efficiently transmit Objects through AJAX utilizing bodyParser in node.js express?

Currently attempting to execute: $.ajax({ type:"POST", url:"/psychos", data:JSON.stringify(this.psycho) }) Upon reaching the server, I encounter the following: app.post("/psychos", function(request, respon ...