-1

I thought it would be easy to find an answer to this, but it wasn't. I'm trying to make an api call from a function and then display the response in a different function. What I've got or what I want to achieve:

async getData() {
   const response = await http.get("/api/");
}

async showData() {
   const result = await this.getData();
   console.log(result);
}

Any help is appreciated!

pistevw
  • 432
  • 4
  • 15

1 Answers1

3

The getData method shouldn't need to be declared async. Just make showData an async method and await the getData response.

const getData = () => fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => response.json());

const showData = async () => {
  const result = await getData();
  console.log(result);
}

showData();

Here is the altered code:

getData() {
   return http.get("/api/");
}

async showData() {
   const result = await this.getData();
   console.log(result);
}
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
  • Thank you for the answer, and your time, I appreciate it! I'm not that confident in fetch or api calls. – pistevw Nov 04 '20 at 16:09