score:1

Accepted answer

try try catch:

getweather = async (e) => {
    try {
        e.preventdefault();
        const city = e.target.elements.city.value;
        const country = e.target.elements.country.value;
        const api_call = await fetch(`http://api.openweathermap.org/data/2.5/weather?q=${city},${country}&appid=${api_key}&units=metric`);
        const data = await api_call.json();
        console.log(data);
    } catch(e) {
        console.log('error: ', e);  
    }
}

score:1

use

class app extends react.component{
  getweather = async (e) => {
    e.preventdefault();

    const city = e.target.elements.city.value;
    const country = e.target.elements.country.value;
    try {
        const api_call = await fetch(`http://api.openweathermap.org/data/2.5/weather?q=${city},${country}&appid=${api_key}&units=metric`);

        const data = await api_call.json();
        console.log(data);
    } catch(e) {
       console.log(e);
    }

  }

score:3

just examine the status property of the resolved promise before you try to extract the body with the .json() method.

async function test() {
  const api_call = await fetch(`https://cors-anywhere.herokuapp.com/http://example.com/fake/fake`);
  console.log(api_call.status);
}

test();

score:5

regardless of using async/await or promise chaining, the fetch api returns a promise containing a response object. the response object contains a status property which returns an http status code. before you call the .json() method on your response object you can check to see if res.status === 200. for example, the openweather api will return a http status code of 200 for successful requests. so, to check if your api request was successful, you could do the following ...

class app extends react.component{
  getweather = async (e) => {
    e.preventdefault();

    const city = e.target.elements.city.value;
    const country = e.target.elements.country.value;

    const api_call = await fetch(`http://api.openweathermap.org/data/2.5/weather?q=${city},${country}&appid=${api_key}&units=metric`);

    if (api_call.status !== 200) {
        // you can do your error handling here
    } else {
        // call the .json() method on your response to get your json data
        const data = await api_call.json();
    }
  }

you can see more of the response object properties and methods by viewing the mdn documentation


Related Query

More Query from same tag