data.json() is not a function (React)

偶尔善良 提交于 2021-02-11 14:39:41

问题


I have the following code:

 getWeather = e => {
    e.preventDefault();
    const api_call = fetch(
      `http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=${API_KEY}`
    );
    const data = api_call.json();
    console.log(data);
  };

But I keep getting .json() is not a function. Not sure why I am getting that.


回答1:


That's because you didn't wait for the request to end.

Try this instead:

const api_call = fetch(
  `http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=${API_KEY}`
).then(res => res.json()).then(console.log);



回答2:


Fetch returns a promise, so in your case you would want to use async/await:

getWeather = async e => {
    e.preventDefault();
    const api_call = await fetch(`http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=${API_KEY}`);
    const data = api_call.json();
    console.log(data);
};

Or you could use .then() and .catch() blocks:

getWeather = e => {
    e.preventDefault();

    fetch(`http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=${API_KEY}`)
    .then(res => res.json())
    .then(res => {
        console.log(res)
    })
    .catch(err => console.log(err))
};



回答3:


Use await on fetch (returns a Promise)

getWeather = async e => {
    e.preventDefault();
    const api_call = await  fetch(`http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=${API_KEY}`);
    const data = api_call.json();
    console.log(data);
  };



回答4:


Put await before fetch and make the function async

 getWeather = async e => {
e.preventDefault();
const api_call = await fetch(
  `http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=${API_KEY}`
);
const data = api_call.json();
console.log(data);

};



来源:https://stackoverflow.com/questions/60839014/data-json-is-not-a-function-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!