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

What is the best way to make IE 10 display a pointer instead of an I-bar for a select list?

Is there a way to make IE 10 display a pointer instead of an I-bar when selecting from a list? Despite trying various methods found in similar questions, I have been unable to resolve this issue. The cursor: pointer property works as expected on other br ...

In Angular, the exclusion of a name attribute in a textarea element does not automatically generate an instance

I came across this jade template for creating a modal dialog in Angular Material. Unfortunately, I couldn't convert it to HTML because the jade site was not working. md-dialog(aria-label='Reject', ng-cloak='') form(name="rejecti ...

Unexpected outcomes when generating jQuery pages using CSS

I have created a piece of JavaScript code that populates 3 divs with icons in even rows. However, I am facing an issue where my first two rows align as expected, but the third row starts aligned with .col-5. Can you help me troubleshoot this? function row ...

Utilize pg-promise for inserting data with customized formatting using the placeholders :name and :

After reviewing the pg-promise documentation, I came across this code snippet: const obj = { one: 1, two: 2 }; db.query('INSERT INTO table(${this:name}) VALUES(${this:csv})', obj); //=> INSERT INTO table("one"," ...

Tips on incorporating CKEditor4 wiris MathML formulas into react JS

I am having trouble displaying MathML in the DOM. When I try to render it, the output is not showing correctly in the Editor. I am utilizing CKEditor4 Let me share the code below to provide more context on what I have attempted so far App.js file: impo ...

Vue struggles to handle data coming from a composable function

For my specific case, I need to verify whether the user has subscribed to my product through both Stripe and Firebase. To accomplish this, I created a composable function that checks for the current subscription in the Firebase collection. If the user cur ...

Get information that has been uploaded using ajax

I need help with my code for sending data via ajax to an update.php page. $(document).ready(function() { $("#modify").click(function() { var a = $("#a").val(); var b = $("#b").val(); var c = $("#c").val(); $.ajax({ type: "POST", ...

Modify picture properties when listbox is altered using jQuery

I need to set up a unique album gallery display where different folders are selected based on the item chosen in a selectbox. Below is the HTML code: <select name="album" id="album" onChange="changeimage();"> <option value="0" selected disab ...

Enhancing User Experience in VueJS with Pug Templates and Transitions

Managing multiple 'pages' of content within a multi-step process can be challenging, especially when trying to incorporate VueJS's transition feature for a carousel-like slide in/out effect. The contents being transitioned are stored in sepa ...

Highcharts failing to connect the dots with lines between data points

UPDATE: After some investigation, it turns out that the issue stemmed from inconsistent intervals. By following the solution outlined in this post, the problem was easily resolved. I have implemented highcharts to create a chart, where the initial data po ...

Transition smoothly between two images with CSS or jQuery

I am working on a project where I need to implement a hover effect that fades in a second image above the initial image. The challenge is to ensure that the second image remains hidden initially and smoothly fades in without causing the initial image to fa ...

What is the best way to trigger the Javascript blur event following a click event that results in the element losing focus

Encountering this issue multiple times has left me dissatisfied with the solutions I've implemented in the past. The challenge lies in dealing with an input box that triggers a validation process on blur, while also having a button that populates the ...

How to delete the final character from a file stream using node.js and the fs module

My current project involves using node.js to create an array of objects and save them to a file, utilizing the fs library. Initially, I set up the write stream with var file = fs.createWriteStream('arrayOfObjects.json'); and wrote an opening brac ...

What is the best way to conceal a global component like a navbar on specific routes?

Most of the pages on my vuejs SPA feature a top navbar component, but there are certain views like the login page where I do not want it to be displayed. My current solution involves importing the navbar and adding it to each view separately when needed. ...

React: Assigning a unique className to an element in a list

In the code snippet below, I am attempting to add a className based on the state of the checkbox. While the className is being added correctly, the issue arises when it gets applied to all elements in the list upon checking/unchecking any checkbox. I aim ...

What is the best way to remove excess content that falls outside the viewBox?

Is there a function or method to trim a path that extends beyond the viewbox rather than simply concealing it? I am currently using svg-edit, which has a specific viewbox or canvas area. Any elements drawn outside of this canvas remain hidden. However, wh ...

Creating a video game HUD effect using JavaScript and HTML5

In an attempt to recreate a video game HUD using HTML5, I have styled a div with CSS properties to resemble a game overlay. When a navigation link is clicked, the div should transition from a hidden state (display:none), then flash twice rapidly before fad ...

Guide to implementing tooltips for disabled <li> elements in AngularJS

I have a list of items that are displayed using the following code: <li class="dropdown-item" data-toggle="tooltip" uib-tooltip="tooltip goes here" data-placement="left" data-ng-repeat="result in items.results.contextValues.rows " ...

Functionality issue with Datatables within JQuery-UI Tabs

I'm experiencing an issue with the compatibility of jQuery-UI tabs and Datatables. My goal is to create a scrollable table that displays information fetched from a database. Upon initially loading the page, the table appears like this. It looks like ...

Inserting an item into ng-model within a dropdown menu

I have a select box populated with data from my backend. This data is an array of objects: [Object { superkund_id="4", nod_id="12068", namn="Växjö Fagrabäck"}, Object { superkund_id="5", nod_id="9548", namn="Halmstad Bågen / Pilen"}] I am using ng-o ...