Home > front end >  Setting variables in Vue 2 using Fetch API: Async Task
Setting variables in Vue 2 using Fetch API: Async Task

Time:07-23

am relatively new to async tasks but I cant comprehend why my fetch API wont set my vue variable but on console.log it shows the Variable. I’ve tried Async/Await in vain. See the code segment below on my .vue component.

data(){
  return{
    pg:’’
  }
},
methods:{
  insertData(){
    this.insertDataAPI()
    console.log(this.pg)  //THIS GIVES EMPTY STRING INSTEAD OF FETCHED DATA
  },
  insertDataAPI(){
    fetch(‘EndPoint’, {
      method:'POST',
      headers:{
        // some headers
      },
      body:JSON.stringify({
        // some data
      })  
    }).then( res => res.json())
      .then(async page =>this.pg = await page  //Console.log logs the page fine
                                                   // but variable pg is not set
      ).catch( (err) => {
        console.log(err)
      });
  }
}

CodePudding user response:

async/await is a different handler for promise.then().catch(). As fetch returns a promise you can use both

Option 1, await the fetch:

methods: {
  insertData() {
    this.insertDataAPI();
    console.log(this.pg);
  },
  insertDataAPI() {
    const response = await fetch(‘EndPoint’, {
      method:'POST',
      headers:{
        // some headers
      },
      body:JSON.stringify({
        // some data
      })
    });
    this.pg = response.json();
  }
}

Option 2, await the insertDataAPI:

methods: {
  async insertData() {
    await this.insertDataAPI();
    console.log(this.pg);
  },
  insertDataAPI() {
    return fetch(‘EndPoint’, {
      method:'POST',
      headers:{
        // some headers
      },
      body:JSON.stringify({
        // some data
      })  
    }).then(res => res.json())
      .then(page => this.pg = page)
      .catch( (err) => {
        console.log(err)
    });
  }
}

CodePudding user response:

let's try to read about the way async/ await work

you can try on Axiost lib for easier to fetch APIs

  • Related