DEV Community

Tom Yotwongjai
Tom Yotwongjai

Posted on

Fetching weather API Using async/await & axios in react.

I learn an easy way to retrieve weather data from weathermap.org without too may lines of codes and I want to share with you. Let me know if there's a better way to do so.

  1. I install axios into my react weather application:
    //Axios is use to get HTTP request data from external sources like weather api.

npm install axios

  1. I Go to openweathermap.org and create an account to get url and custom generated api key. Once account is created, click API Keys to create your api key. You will need the base URL & your custom key as shown below:
https://api.openweathermap.org/data/2.5/
[custom api key]

Define my api key in my react file. I have in my app.js file:

const apiKeys = {
  key: 'e902985907738b357b6a7c7a2651a108',
  base: 'https://api.openweathermap.org/data/2.5/',
};
Enter fullscreen mode Exit fullscreen mode

import axios to my app.js file:

import axios from 'axios';
Enter fullscreen mode Exit fullscreen mode

In my function called App I create async function:

async function fetchWeather(e) {
    e.preventDefault();
    try {
      const response = await axios(
//The base URL & api key
        `${apiKeys.base}weather?q=${city}&units=metric&APPID=${apiKeys.key}`
      );
      updateWeather(response.data);
//console.log to see if there's data
console.log(response);
    } catch (error) {
      setError({ message: 'Not Found' });
console.log(error);
    }
  }
Enter fullscreen mode Exit fullscreen mode

The code above work like this: Async tell react that the function fetchWeather is asynchronous and await for axios to retrieve the data once it finish, return the result to response variable. Putting the code into try/catch block will catch an error of the code that could potentially fail. In this case if
there's no location found, the error message will be shown.

There you go! I hope this is helful. Leave any comment and constructive criticism. :)

See you next time!

Source code: https://github.com/tomyotwongjai/react-weather-app

Top comments (0)