Integrating Weather Data and Analytics into a Web Application Using React

It’s not hard to see the dramatic effect weather can have on global businesses. Look no further than the Ever Given ship mishap and the amount of money that was lost while the ship was stuck in the Suez Canal. On March 23rd, 2021, the ship was struck by a sandstorm, and its steering system couldn’t keep the ship in a straight position while inside the canal. It took six days for the ship to be freed, blocking other ships from using the canal and causing massive headaches in the global logistics and supply chain.

This is where an accurate weather forecast in real-time can be very helpful to the person in charge of managing those routes, and to the ship Captain and navigators who can use those insights to make the right decisions at critical times along the way. The weather forecast can be included as a widget inside the logistics business application and accessible to all route managers and drivers.

Let’s take a look at how a simple React component that will display the current weather condition for any location. This component can be integrated into any web application using the Tomorrow.io weather API to get quality weather data.

The Tomorrow.io Weather API data source

Once you’ve signed up for a developer account, you can start by creating the request to get the data you need.

const queryString = require("query-string");
const moment = require("moment");
const fetchCurrentWeather = (coordinates) => {
 const getTimelineURL = "https://api.tomorrow.io/v4/timelines";
 const apikey = [API_KEY];
 let location = coordinates.join(",");
 const fields = ["precipitationIntensity", "windSpeed",       
                 "temperature"];
 const units = "imperial";
 const timesteps = ["current"];
 const now = moment.utc();
 const startTime = moment.utc(now).add(0, "minutes").toISOString();
 const timezone = "America/New_York";
 const getTimelineParameters = queryString.stringify(
   {
     apikey,
     location,
     fields,
     units,
     timesteps,
     startTime,
     timezone,
   },
   { arrayFormat: "comma" }
 );
 return fetch(getTimelineURL + "?" + getTimelineParameters,
              { method: "GET" });
};
export default fetchCurrentWeather;

The above code will request the weather data from the current location for which it receives the coordinates. The requested data will have the following weather fields: temperature, wind speed, and precipitation intensity, and those fields will be measured using the imperial system.

The function fetchCurrentWeather is exported and then used in the React Weather Component that we will see in the following section.

React Weather Component

Now that we have the request function ready, let’s look at the component that will show the weather data.

 import React, { useState, useEffect } from "react";
import fetchCurrentWeather from "./WeatherService";
const WeatherComponent = (props) => {
 const { location } = props;
 const [data, setData] = useState({
   timelines: [
     {
       intervals: [
         {
           values: {
             temperature: 0,
           },
         },
       ],
     },
   ],
 });
useEffect(() => {
   fetchCurrentWeather(location.coordinates)
     .then((result) => result.json())
     .then((json) => {
       setData(json.data);
     })
     .catch((error) => console.error("error: " + error));
 }, []);
const { temperature, precipitationIntensity, windSpeed } =
   data.timelines[0].intervals[0].values;
return (

 

 

{`${Math.round( temperature )}° F`} {location.label}

 

{`${precipitationIntensity} IN`} {`${windSpeed} MPH`}

 

 

 

); }; export default WeatherComponent;

The code above will use the function fetchCurrentWeather to get the weather data when the component is loaded and will store it in its state in the field data. The HTML structure of the component will display the current temperature, the rain intensity, and the wind speed for the selected location.

With the component ready, it’s just a matter of importing it into your application and using it.

 



Wrapping up

The example above is just a simple sample of the potential benefits of using a weather API. It can be extended to incorporate more powerful weather data features like:

  • Events — monitor and receive alerts about adverse events for a specific set of locations
  • Map — see weather conditions on a map and find out when, where, and how your business can be impacted so you can be prepared
  • Route — check what obstacles are being created by the weather that can put your business at risk, increase costs, or create delays

After integrating the above features in the existing Weather Component, incorporating the components into another web application will be easy, and the end application will get richer.

Another possible improvement is to include a feature that provides the forecast for the coming week and automatically collects data in real-time to update the component. This way, the weather data will become more accurate as the truck moves along the route.

Happy coding!

More from Tomorrow.io