46
Fetching weather API Using async/await & axios in react.
//Axios is use to get HTTP request data from external sources like weather api.
npm install axios
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/',
};
import axios to my app.js file:
import axios from 'axios';
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);
}
}
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's no location found, the error message will be shown.
Source code: https://github.com/tomyotwongjai/react-weather-app
46