Home > Blockchain >  Fetch API inside a class function
Fetch API inside a class function

Time:12-11

I'm having trouble with destructuring an object that is returned from the fetch api in my Aztro class.

I've tried various way to destructure it at random with no success....

If i return it instead of console logging, how do i access it? See the code and comments for further clarification of my questions.

The reason i want to do this is because the api will only return one zodiac sign at a time.

 class Aztro {
  constructor(sign){
    this.sign = sign
  }
  getData(){
    return fetch('https://example/?sign='   this.sign   '&day=today', {
      method: 'POST'
    })
    .then( response => response.json() )
    .then( data =>  {
      console.log(data) // how do I destructure this if it's returned and not just console.log()
    })
  }
}

let aries = new Aztro('aries')      // Can pass in zodiac signs to fetch data
let aquarius= new Aztro('aquarius')

aries.getData()     // this logs the json data in the console....

// EDIT this is how I tried to destructure it 

const {description} = aries
const {description} = aries.getData() // this returns Object promise when i tried to output it to the dom 
const {description} = Aztro
 

CodePudding user response:

You can access the fetched data in two manner:

1- using promise chain, like this:

aries.getData().then(data => console.log(data))  

2- using async/await to fetch data.The important point in using async/await is that you have to call await keyword just inside an async function (the reason I defined app function in below code) like this:

class Aztro {
  constructor(sign){
    this.sign = sign
  }
  async getData(){
    const response = await fetch('https://example/?sign='   this.sign   '&day=today', {
      method: 'POST'
    })
    const data = await response.json();
    return data;
  }
}

async function app(){
  let aries = new Aztro('aries')      // Can pass in zodiac signs to fetch data
  let aquarius= new Aztro('aquarius')
  const data = await aries.getData();
  console.log(data);
}
app();
  • Related