0

i wont to make class to handle fetch data from api, please help my trouble:

class Api{
    static getAll(){
        fetch("https://covid-193.p.rapidapi.com/statistics", {
        "method": "GET",
        "headers": {
        "x-rapidapi-host": "covid-193.p.rapidapi.com",
        "x-rapidapi-key": "c44a47562cmsh6ff0d107514bccfp146d00jsn876b11317ac5"
        }
        })
        .then(function(response) {
            return response.json()
        })
        .catch(function(err) {
            console.log(err)
        })
    }
}

export default Api;

when i call Api.getAll() in app.js like this:

import Api from "./api.js"
console.log(Api.getAll())

its not console anything , just console undefine. but if i console inside .then() like this

.then(function(response) {
            console.log(response.json())

the result in console is

undefine
result json

and if i change the key to get eror, the .catch() not work also.

thanks,

blanksix
  • 340
  • 1
  • 16
  • 1
    `fetch` returns a [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise), if you want to return the response data, you either need to return a `Promise` that resolves to it or use [`async/await`](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await) – Elan Hamburger Apr 27 '20 at 03:30
  • Add `return` in front of `fetch` to return the promise. Then your _"console inside .then()"_ will work as expected – Phil Apr 27 '20 at 03:41

1 Answers1

1

fetch will return a promise. So, you need to handle promise to get the data.

Here's an example.

fetch("https://covid-193.p.rapidapi.com/statistics", {
        "method": "GET",
        "headers": {
        "x-rapidapi-host": "covid-193.p.rapidapi.com",
        "x-rapidapi-key": "c44a47562cmsh6ff0d107514bccfp146d00jsn876b11317ac5"
        }
        })
        .then(function(response) {
            return response.json()
        })
        .catch(function(err) {
           // console.log(err)
        }).then(data => console.log(data))

So, in your example you need to handle promise returned like :-

add return before the fetch("https://covid-193.p.rapidapi.com/statistics", {}) and then,

Api.getAll().then(data => console.log(data));

You can find more information about fetch API at

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Atul Sharma
  • 9,397
  • 10
  • 38
  • 65
  • 1
    You're missing `return` in front of `fetch()`, `.then(data => console.log(data))` will make this resolve with `undefined` and you've removed OP's `response.json()` for some reason – Phil Apr 27 '20 at 03:39