Guide to cycling through Promise results and populating a form

I have an asynchronous function that returns a Fetch Request:

  async fetchDataByCodOS(codOS){      
    const res = await fetch(
      'http://localhost:5000/cods/'+codOS,
        {
          method:"GET"
        }
    ).then(res => res.json())
    return res
  }

I am able to print a Promise Object, now I need to iterate through it. By using @input:change() in v-text-field

change(){
   this.fetchDataByCodOS(this.codOS).then( result => console.log(result) ); // Returning Object inside Array
}

I want to just grab the JSON Object:

change(){
   this.fetchDataByCodOS(this.codOS).then( result => result.forEach(
       el => console.log(el)   
   ));
}

Now I can access the elements inside the object, but I'm unable to fill my form with it, for example using v-model:

<v-text-field label="ID" v-model="ID" disabled> </v-text-field>

I thought the right way to fill it was to create an empty object called ob in data which I could use inside forEach, but I didn't do that.

export default {
data(){
 return {
   ob: {
    //values here   
       }
  }
 }
}

Can you suggest a better practice or way to make this work?

Updating

VUE FORM:

      <v-text-field 
        label="Id. OS"
        v-model="codOS"
        @input="change()"  
      > 
      </v-text-field>
    </v-col>
    <v-col cols="12" md="9">
      <v-text-field label="ID"  disabled> </v-text-field>
    </v-col>
    <v-col cols="12" md="4">
      <v-text-field label="NAME"  disabled> </v-text-field>
    </v-col>
    <v-col cols="12" md="8">
      <v-text-field label="CITY"  disabled> </v-text-field>
    </v-col>                
    <v-col cols="12" md="9">
      <v-text-field label="FONE"  disabled> </v-text-field>
    </v-col>    

<script>
  export default {
    data (){
      return{
        codOS: '',
      }
    },
    methods:{
      autocomplete(){
        if(this.codOS.length == '5'){
            const data = this.fetchDataByCodOS(this.codOS);
            //data.then(r =>  console.log(r)); // Here I just grab the data object, but I'm trying to remove the array, so.
           data.then(r => r.forEach(el =>
              console.log(el) 
               //I think her I want to take el.nameObject and assign to v-model
            ))

        }
      },
      // Change my function according MAX
      async fetchDataByCodOS(codOS){      
        const res = await fetch(
          'http://localhost:5000/cods/'+codOS,
            {
              method:"GET"
            }
        )
        const json = await res.json()
        return json
      }
    }
  }
</script>

What console is showing:

Promise {<pending>}
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: Array(1)
0: {ID: "1", NAME: "EDDY", CITY: "NEW YORK", FONE: "6456465465456"}
length: 1
__proto__: Array(0)

Add.vue?5f53:71 
{ID: "1", NAME: "EDDY", CITY: "NEW YORK", FONE: "6456465465456"}
ID: "1"
NAME: "EDDY"
CITY: "NEW YORK"
FONE: "6456465465456"
__proto__: Object
   

Answer №1

Avoid Mixing Async/Await with Then Syntax

When you have access to async/await syntax, there is no need to mix it with the then function. The async/await syntax transpiles down to the then function, making them redundant when used together.

  • The fetch() function is asynchronous and should be awaited
  • The json() function is also asynchronous and requires await to resolve properly
  async fetchDataByCodOS(codOS){      
    const result = await fetch(
      'http://localhost:5000/cods/'+codOS, { method:"GET"}
    )
    const json = await result.json()
    return json
  }

Handling Data Binding

To bind data asynchronously, you can make a call in the mounted method and set the retrieved data on the component's data, which can then be passed into the template for display.

An example using the open trivia API showcases iterating through results using v-for before utilizing handlebar syntax for binding.

Binding Form Inputs

Vue.js allows for direct binding of input models as shown below:

<input v-model="item.category">

A working example similar to this setup can be found on this sandbox https://codesandbox.io/s/max-vue-fetch-iterate-wc5qm?file=/src/App.vue

Further resources that aided in crafting this approach include:

https://www.sitepoint.com/fetching-data-third-party-api-vue-axios/

https://v2.vuejs.org/v2/guide/list.html

https://v2.vuejs.org/v2/guide/forms.html

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

Having trouble retrieving the iframe document using JavaScript

I'm currently facing an issue when trying to fetch an image from a website (not specifically Bing, this problem arises with every site). Upon running the code, it seems to be failing at the 'if' statement, indicating that there might not b ...

Mesh does not display texture in three.js

I've been attempting to add a texture to my sphere mesh using the code snippet below: var loader = new THREE.TextureLoader(); var balltex = loader.load("pic1.jpg"); var ballmat = new THREE.MeshBasicMaterial({ map: balltex }); var ballgeo = new THREE ...

Tips for displaying the sum of a grouped field in the balloonText using Amchart

I recently started working with Amcharts and I am seeking advice on what I may be doing incorrectly. Below is the snippet of my JavaScript code: var chartData1 = []; generateChartData(); function generateChartData() { var month = new Array( ...

The express route parser is incorrectly detecting routes that it should not

I am encountering an issue with the following two routes: router.get('/:postId([0-9]*)', handler) router.get('/:postId([0-9]*)/like', handler) The first route is intended to only capture URLs like /posts/4352/, not /posts/3422/like. ...

Discover the process of converting the texture in three.js to WebGL

I have received two texture objects containing position and normal data: var tx1 = gpuCompute.getCurrentRenderTarget( positionVariable ).texture; var tx2 = gpuCompute.getCurrentRenderTarget( normalVariable ).texture; These textures are generated using GP ...

Is there a way to incorporate expandable content on a Drupal node page using Javascript?

Is there a Drupal Module available that can display a trimmed version of content on the node page and expand it when clicking on a "Read More" link? Thank you! ...

Encountering difficulties triggering the click event in a JavaScript file

Here is the example of HTML code: <input type="button" id="abc" name="TechSupport_PartsOrder" value="Open Editor" /> This is the jQuery Code: $('#abc').click(function () { alert('x'); }); But when I move this jQuery code to a ...

Adding an id to a ul tag using JavaScript

I am trying to dynamically add an ID called "myMenu" using JavaScript to a ul element for a search filter. Unfortunately, I am unable to directly access the ul tag to change it, so I need to do it via JavaScript. As I am new to JavaScript, I am looking t ...

Refresh the JavaScript graph with new data from the AJAX request

Seeking assistance in updating my javascript chart data using ajax data retrieved from a database. The specific chart being referenced is an apex chart. After submitting a form via ajax, the returned result is as follows: type: "POST",crossDomain ...

What could be causing the error "SyntaxError: Expected token ']' to appear" to pop up?

Recently, I have been working on implementing a 'night mode' feature for a website. However, every time I attempt to execute the script, an error message pops up: "SyntaxError: Expected token ']'" on line 9. The problematic line in ...

"Encountering an issue with the Foreach function in nextjs when iterating through

I attempted to iterate through each character in a String, but the SPANS are not displaying. What could I be doing incorrectly? export default function Work() { const logoText = "The future starts here."; return ( <div className=& ...

Utilizing a JavaScript variable within a jQuery function as an attribute

var image = "path.png"; Is it possible to include the 'image' variable in the jQuery function like this? $('#mapfoto').prepend('<img id="theImg" src="http://path.gr/" + image />'); ...

Embracing right-to-left (RTL) languages

I am looking to create a website that can support both left-to-right (LTR) and right-to-left (RTL) languages seamlessly. My goal is to have the text direction switch automatically to RTL if the content is in an RTL language. Additionally, I want the input ...

Invoking one service from another service in AngularJS

I'm trying to access a service from another service and use the returned object for some operations. However, I keep encountering a TypeError: getDefinitions is not a function error. Here is the code for my services and controller: definitions.servi ...

When attempting to send a request for the JSON body to Node.js using the await fetch method, I encountered an issue

Recently, I started working with node js and attempted to fetch JSON data using the code below: const req = await fetch( "http://localhost:3000/api/auth/signin", { method: "POST", header:{ 'Accept':&apo ...

Vue JS - Show the second option in the select menu once the first option is disabled

Can anyone assist me with displaying the second option in a select drop-down menu after the menu is disabled? The select menu will be disabled if there are only two options available. However, instead of showing the default 'Select nationality' ...

Update the content of the document element by assigning it a lengthy string

I'm utilizing JQuery to dynamically assign content to a div element. The content has numerous lines with specific spacing, so this is the approach I am taking: document.getElementById('body').innerHTML = "Front-End Developer: A <br/> ...

Using AngularJS to pass the output of a unique filter to another custom filter

I have successfully developed two custom filters and am attempting to utilize them both within an ng-repeat loop. Is there a way for me to pass the output of the first filter as an input for the second one? I attempted using 'as' keyword in ng- ...

Determine if the browser displays <select multiple> as a modal dialog

Is it possible to use JavaScript to detect whether a specific browser displays a focused <select multiple> element as a popup or strictly as an inline box? On certain platforms, like the Android Browser and iOS Safari, the appearance of a popup can ...

Steps to implement password validation that matches in vuetify

I am looking to implement a profile form with two fields, password and rePassword, where both should match. I've tried various codes and approaches from the web, some worked but didn't quite fit in with my code. Below is the code snippet: Prof ...