React Beginner: Part V

Murli Prajapati
Bit Shift
Published in
5 min readMay 14, 2018

Fetching and parsing forecast data

In previous article, we finished all of our app’s components and learned a very useful concept of state lifting. This article will take you through data fetching using OpenWeatherMap (OWM) API and data extraction for different components.

Installing axios:

We are going to use axios for data fetching. So install axios.

npm install axios --save

Getting OpenWeatherMap API key:

1. Go here https://home.openweathermap.org/users/sign_in. Login or register yourself.

2. Once you log in, click on API Keys tab. You will find a key there.

Fetching forecast data:

Import axios in App.jsx like this:

import axios from 'axios';

The old and boring way of fetching forecast data is to make user to enter the city or area code but the new and exciting way is getting users device location and fetching the data. We are going to do both…YES!!

You know the lifecycle methods/hooks we talked about in Part II, it is the time to use one of them. We are going to use componentDidMount hook to ask for location access using HTML5/JS GeoLocation API. It is very simple…Trust me.

Before we do that, add some variables to App’s state.

The idea here is that when the user allows device location access we will add the coordinates to latLng array and then will fetch the forecast data. Once we receive the data we will parse it according to our app’s components. E.g. todayComponentData will hold data for TodayComponent and so on.

But what if the user denies the access…then we will fetch data using the old way…the search box way and then the rest of the flow will be same as explained above.

So ask for the permission and update the state.

Once we have the coordinates we are adding them to the state. Simple right…I told ya.

Let’s create a function that will call this OpenWeatherMap API based on whether we have lat-lng or city/zipcode.

Don’t forget to put your api key that you got earlier in API_KEY variable.

OWM has two different API URL formats, one for lat-lng and another for city/zipcode. So based on the hasLatLng variable value we are creating the queryParams string. So the final URL may look like this:

// hasLatLng = true;
https://api.openweathermap.org/data/2.5/forecast/daily?lat=35&lon=139&units=metric&cnt=7&appid=123456789qwerasd

or like this:

// hasLatLng = false;
https://api.openweathermap.org/data/2.5/forecast/daily?q=London&units=metric&cnt=7&appid=123456789qwerasd

Here cnt=7 shows that we are going to fetch forecast of 7 days. At the end, we are returning a Promise having the forecast data using axios.

With our core function in place, we will now call this function in notifyStateChange function.

We will call the fetchWeatherForecast function only if we have either lat-lng or city/zipcode.

If you now run the app and allow the location permission you should see the forecast data in console. Have a glance at the api response as we are going to extract specific values from it very soon.

To Kill A Tiny BUG:

With the location permission allowed if you enter any city/zipcode in the search box, the fetchWeatherForecast function will not consider it because it only checks for latLng and that is available because we have given the permission.

To solve this bug, we need to reset the latLng variable in the state when the user submits the query. We will do this in onSearchSubmit function of App.jsx.

Here is the solution,

So now when you search for any city/zipcode, hasLatLng variable will be false and the queryString will be considered for data fetching.

You killed it.

Doing a lot of Extraction…a lot:

Now we have the forecast data available we will parse it and divide it for different components. We will start off with Navbar as it is the simplest one.

Add the following function in App.jsx class.

Here we are just taking the city name and the country and returning them as combined string.

Let’s move on to data extraction for TodayComponent.

That’s quite long code…let’s break it down.

Single day response

forecastData.list contains forecast data for next seven days and the first element in the list has today’s data. We are storing that in todayForecast variable.

A single item in forecastData.list looks like this.

As you can see the data we want for TodayComponent is available straight away except today’s day and date because the date (dt field) is in Unix timestamp (time in seconds). We will use JS built-in Date class to extract the day and date.

A cutout of extractDataForTodayComponent function

Date class of JS works with time in milli-seconds that’s why we have multiplied dt with 1000.

Next comes the this.getDay function. This function takes the date class object and returns the string value of a day of the week. Date.getDay() returns a number ranging from 0–6. 0 for Sunday and 6 for Saturday. We are just taking the number and getting the corresponding day name from the dayNames array.

We’ve created a separate function for this because day name are also going to be used in ListComponent.

After day comes the date. We are creating the date in this format: April 5, 2018.

We’ve applied the same techniques as in getDay function to get the month string. Date.getMonth() returns a number between 0 to 11. 0 for January and 11 for December. We have stored the mapping in monthNames array.

Rest of the code in the gist is self-explanatory as we are just accessing values form JSON object.

Extracting data for List and Graph component:

We are going to this in a single function as both components deal with same data.

We are iterating over the forecast. list array and taking day, weatherId, description and temperature for list component and just day’s temperature for graph component.

With the completion of this function, we have all the data ready in those function, we just need to call them and add it to the state. So let’s do that.

This doesn’t need any explanation…pretty straight forward…Right.

Yeah…finally, networking is done, data is ready to go into components and our app is about to complete.

We are left with only two steps, sending data to components and deployment. Let’s head to our series finale to be done with those remaining steps

Series Finale: React Beginner: Part VI

If you liked this article don’t forget to clap 👏. If you have any suggestion or query feel free to post here in comments or ping me on twitter.

--

--

Murli Prajapati
Bit Shift

Full Stack Developer | Android Developer | Hobbyist Gamer