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 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 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:
[custom api key]

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

const apiKeys = {
  key: 'e902985907738b357b6a7c7a2651a108',
  base: '',
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) {
    try {
      const response = await axios(
//The base URL & api key
//console.log to see if there's data
    } catch (error) {
      setError({ message: 'Not Found' });
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:

Top comments (0)