Build a mini weather web with React - 0x02

Welcome back! Now that we have completed the setup of our development environment, we can dive into coding for our mini weather web app. The app’s layout is inspired by a renowned weather forecasting company called AccuWeather. Once we’re done with the coding phase, our weather app will resemble the following image. As we can see, this webpage incorporates essential features that a weather app should have, including the ability to search city weather by keyword, a rainfall forecast radar, automatic location detection, and more.

Figure 1

In this section, we will explore the process of fetching weather data. Numerous third-party weather data service providers are available, but for our project, we will utilize the OpenWeatherData API to retrieve the required weather data. OpenWeatherData offers a comprehensive global weather data API that we could seamlessly integrates with our applications.

To get started, visit https://home.openweathermap.org/users/sign_up and create your personal account. Once you have completed the registration process, you can access all the APIs by visiting https://openweathermap.org/api.

Figure 2

We can subscribe “One Call API 3.0”. It’s free for 1,000 queries per day, and it provide enough data to complete this web app. And as for city search, we could use Geocoding API (https://openweathermap.org/api/geocoding-api) to implement city search feature.

In the code, we could use axios to send a HTTP request, which is a famours Javascript library to help us make HTTP reqeust more easier. And we could wrap our http request code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// api.js
import axios from "axios"

const OPEN_WEATHER_KEY = '< Paste your API Key here >'
const OPEN_WEATHER_HOST = 'https://api.openweathermap.org/data/3.0'

const api = function(method, url, params) {
return new Promise((resolve, reject) => {
params.appid = OPEN_WEATHER_KEY

axios({
url: `${OPEN_WEATHER_HOST}${url}`,
method: method,
params: method === 'get' ? params : undefined,
data: method !== 'get' ? params : undefined,
})
.then((response) => resolve(response.data))
.catch((err) => {
console.log('fetch data error', err)
})
})
}

const apis = {
get: (...args) => api('get', ...args),
post: (...args) => api('post', ...args)
}

export { apis }

As shown in the above code, we encapsulate the necessary code and set the API Key, host and some custom settings within it. To initiate an HTTP request, simply use the following code snippet:

1
2
3
4
5
6
7
8
9
apis
.get('/onecall', {
lat: lat,
lon: lon,
units: 'metric'
})
.then((responseData) => {
// do something with response Data
})

View full code base of the weather app via my github: react-weather