Arrays in Vue Data

After creating an array and pushing data into it, the array turns into a proxy, preventing me from using JavaScript array functions on it.

export default {
  name: 'Home',
  components: { PokeList, FilterType, SearchPokemon},
  data() {
        return {
            pokemons: [],
            numOfPokemon: 151,
            types: []
        }
    },
    methods: {
        async prepairPokeIds() {
            for (let i = 1; i <= this.numOfPokemon; i++){
                
                await this.fetchPokemonData(i)
            }
        },
        async fetchPokemonData(id) {      
        try {
            const res = await fetch(`https://pokeapi.co/api/v2/pokemon/${id}`)
            const data = await res.json()
            this.types.push(data.types[0].type.name)
            this.pokemons.push(data)
            return data
        } catch (error) {
            console.log(error)
        }
        },
        async test(){
          console.log(this.types.length)
        }
    },
  async created() {
      this.prepairPokeIds()
      await this.test()
      console.log(this.pokemons)
      console.log(this.types)
  }
}
</script>

Even though there is data inside the proxy target, the console.log within the test function returns a value of 0. Why is that?

Answer №1

Check out the code snippet below:

async created() {
  this.preparePokeIds() // sends a request and executes line below
  await this.test()
  console.log(this.pokemons)
  console.log(this.types)
}

The function this.preparePokeIds() will trigger the first request in a loop, then control returns to the created method where it will execute await this.test(). This will immediately log console.log(this.types.length), resulting in a value of 0 at that time.


The following code should log the correct value since it runs after the resolution of the first request.

async preparePokeIds() {
   for (let i = 1; i <= this.numOfPokemon; i++){      
     await this.fetchPokemonData(i)
     console.log(this.types.length)
   }
},

Alternatively, you can return promise(s) from preparePokeIds() and await it before executing this.test().

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

React Header Component Experiencing Initial Scroll Jitters

Issue with Header Component in React Next.js Application Encountering a peculiar problem with the header component on my React-based next.js web application. When the page first loads and I begin scrolling, there is a noticeable jittery behavior before th ...

Using ReactJS to strip HTML tags from JSON response

I'm having trouble figuring out how to strip HTML tags from a JSON response in reactjs. Here's the JSON response: { "price": "26,800.98", "diff": "<!--daily_changing-->+13.44 (+0.05%)&nbsp;& ...

JavaScript code that functions similarly to VLOOKUP, allowing you to map input values from one field to

As a beginner in HTML and JavaScript, I am trying to create a simple form that automatically populates a specific "Customer Code" when a "Customer Name" is selected from a dropdown list (similar to an Excel VLOOKUP). However, the examples I found on Stack ...

Utilizing Vue.js API to filter out distinct items in a selection and eliminate any null or empty values

Hello, I'm a newcomer to Vue.js and would really appreciate some assistance. Thank you in advance. I've managed to get the API working smoothly and the Select function is also working well - However, there's an issue with duplicates being d ...

Tips on how to retrieve the value of the second td in an HTML table when clicking on the first td utilizing jQuery

There is a specific requirement I have where I must retrieve the value of the second td in an HTML table when clicking on the first column. To accomplish this task, I am utilizing jQuery. $('.tbody').on('click','tr td:nth-child(1) ...

What are some techniques for managing scrolling within a particular element?

I am currently working with Vue.js and utilizing Element UI components. I want to incorporate a scroll management function to achieve infinite scrolling. To better understand, please refer to the screenshot in the Example section: Despite trying differen ...

Can you explain the purpose of the statement `var MyConstructor = function MyConstructor()`?

Can you explain the distinction between these two code snippets: var NodestrapGenerator = module.exports = function NodestrapGenerator() { yeoman.generators.Base.apply(this, arguments); // more code here }; and: var NodestrapGenerator = module.expor ...

What is the most effective way to loop and render elements within JSX?

Trying to achieve this functionality: import React from 'react'; export default class HelloWorld extends React.Component { public render(): JSX.Element { let elements = {"0": "aaaaa"}; return ( ...

Leveraging CSS or JavaScript for Displaying or Concealing Vacant Content Sections

I'm working on developing a page template that utilizes section headers and dynamically pulled content from a separate database. The current setup of the page resembles the following structure: <tr> <td> <h3> ...

Error in Angular form validation: Attempting to access property 'name' of an undefined value

Recently, I encountered an issue with my form while implementing Angular validation. The goal was to ensure that the input fields were not left blank by using an if statement. However, upon testing the form, I received the following error message: Cannot ...

Pressing the button updates the value in the input field, but the input field continues to

I need some assistance with my e-commerce platform. I am trying to implement a button that adds items to the shopping cart, but I'm encountering an issue where the value in nbrSeats (my list of values) changes in the data, yet the input field displays ...

Error occurred due to an improperly formatted authorization header while attempting to upload an object to S3 using the JavaScript SDK

When attempting to upload an object to Amazon S3 using their JavaScript SDK, I encounter the following error message: <Error> <Code>AuthorizationHeaderMalformed</Code> <Message>The authorization header is malformed; the reg ...

The dynamic data graph generated by HIGHCHARTS Areaspline is not as effective as expected

I need help creating a Dynamic Areaspline graph, but the result is coming out strangely. Does anyone have any ideas on how to fix this and get a smooth series? Here is an example of the issue: http://jsfiddle.net/mchc59nb/1/ chart: { ...

Link the index value of a v-for loop to the id of a newly created component

I need to create components in a loop within my Vue app, but I want each component to have a unique id value like "board-1" based on the index of the loop. Just like how I did it with v-bind:key="component-${block._uid}". How can I make this happen? < ...

Exploring the proper syntax of the reduce() method in JavaScript

Here are two codes that can be executed from any browser. Code1: let prices = [1, 2, 3, 4, 5]; let result = prices.reduce( (x,y)=>{x+y} ); // Reduces data from x to y. console.log(result); Code2: let prices = [1, 2, 3, 4, 5]; let result = prices.red ...

Best practice for resetting jquery datatables for proper functioning

A user on Stack Overflow was seeking a solution for working with DataTables.js and a variable number of columns. The provided solution can be found here: http://jsfiddle.net/gss4a17t/. It's worth noting that this solution relies on a deprecated funct ...

The click event fails to trigger while trying to parse external HTML

Currently, I am working on a project that requires me to load HTML from an external file and insert it into an existing div element. Although the process is successful overall, I have encountered an issue where the .click() events do not trigger when click ...

Issue with preventDefault not functioning correctly within a Bootstrap popover when trying to submit a

I am facing an issue with a bootstrap popover element containing a form. Even though I use preventDefault() when the form is submitted, it does not actually prevent the submit action. Interestingly, when I replace the popover with a modal, the functional ...

A guide to update values in mongodb using node.js

I'm working on tracking the number of visitors to a website. To do this, I've set up a collection in my database using Mongoose with a default count value of 0. const mongoose = require('mongoose'); const Schema = mongoose. ...

Enhance your Vue.js 3 tables with sorting, filtering, and pagination capabilities using this custom component

After extensive research, I am still unable to find an updated Vue.js 3 component that offers sorting, filtering, and pagination for tables without the need for additional requests to a backend API. The options I have come across either seem outdated, are ...