Let’s face it, while it’s fun to write applications from scratch, a lot of software development work involves working with existing code. In this post, we are going to learn how to add a feature to an existing React/Redux app. Following on our previous articles in <list filtering with react/redux> and <component interactivity with react/redux>, we will add a feature to get a weather forecast estimate to help us figure out when is the best time to visit crater lake. In addition, since we are querying an API, we will be learning how to use async actions to retrieve and display the weather.

Here’s an outline of the process we will be following

  1. Adding a date selector component to let the user pick a date for getting the weather.
  2. Getting weather information from the <DarkSky api>
  3. Identifying where and when to update state to incorporate our new weather feature
  4. Handling state changes with async interfaces

Check out the final product on Heroku and get the code on Github.

finished image.png

Adding a date selector

Using the react-datepicker module we’ll create a new WeatherDatePicker component to show the date picker and the forecast results. When the user loads the page they will see “Select a date…”:

date picker.png

After a date is selected, the forecast will be displayed:

date picked.png

Taking a look at the render method in WeatherDatePicker.jsx:

render() {

 return (


 Travel Date:


 placeholderText="Select a date..."


 dateFormat = "YYYY-MM-DD"

 onChange={(selectedDate) => {

 let newDate = this.checkDate(selectedDate)

 if (newDate) {

 this.props.fetchWeather(this.checkDate(selectedDate), this.props.currentLat, this.props.currentLong)


 } }/>

 Forecast: {this.props.weatherSummary}




When the DatePicker is opened and a date is selected, firing the onChange event, we first check the date to make sure it is in the future:

checkDate(selectedDate) {

 if (selectedDate.isBefore(this.props.currentDate)) {

 alert("Please pick a date in the future.")

 return undefined


 else {

 return selectedDate.format("YYYY-MM-DD")



The DatePicker module uses moment.js for the date object. We can use moment’s isBefore method to compare two moment objects, and display an alert if the user picks a date in the past. If the render method receives a valid result, it calls the delegate fetchWeather, passing along the selected date, to retrieve the weatherSummary.

Now we will add the WeatherDatePicker component and the DarkSky attribution graphic to CampFilterApp.jsx:

render() {

 return (

 <div className="container">

 <div><a href=""><img src="" style={{ width: 100 }}/></a></div>


 <h1>Crater Lake Camping</h1>



 <CampFilterList {...this.props}/>


 <WeatherDatePicker {...this.props}/>


 <CampMapContainer {...this.props} />



While we are working with components, let’s also update the Redux store to include the thunk middleware that we’ll be using for the next steps. We just need to add thunkMiddleware to our createStore call. In index.js:

import thunkMiddleware from 'redux-thunk'

const store = createStore(reducer, applyMiddleware(



Adding state and async actions for the weather feature

Now that we have a component to display the weather, lets look into the associated actions and state needed to do the work.

For the weather feature, the following fields are added to the state in index.js and set as props in CampFilterApp.jsx:

currentDate: today,

weatherSummary: "",

currentLat: 42.9456,

currentLong: -122.2,

selectedDate: undefined

The DarkSky API needs a position and date to retrieve the weather. Since our app is localized to Crater Lake we’ll use those coordinates to retrieve the weather. Don’t forget to convert these new state variables to props to send down to the WeatherDatePicker component in CampFilterApp.jsx:

function mapStateToProps(state) {

 return {


 weatherSummary: state.get('weatherSummary'),

 currentDate: state.get('currentDate'),

 currentLat: state.get('currentLat'),

 currentLong: state.get('currentLong'),

 selectedDate: state.get('selectedDate')



To query the API and update the selectedDate and weatherSummary variables we will use thunk middleware and fetch as described in this article from the Redux docs.

To handle an async action, we will split the API call into request and receive actions. Our request action, REQ_WEATHER, will update the selectedDate to the value passed from the DatePicker and weatherSummary to “Loading…” to let the user know the weather info is loading. From action_creators.js:

export function reqWeather(weatherDate) {

 return {

 type: 'REQ_WEATHER',




And the corresponding function in reducer.js:

function reqWeather(state, weatherDate) {

 return state.merge(Map({

 'weatherSummary': "Loading...",

 'selectedDate': weatherDate



For the receive action, RECV_WEATHER, we add a response field to our state to hold the JSON returned by the DarkSky API:

export function recvWeather(weatherDate, result) {

return {



response: result



The corresponding method in reducer.js for parsing the API response into the weatherSummary field:

function recvWeather(state, weatherDate, result) {

 let content = ""

 try {

 let tempMax =[0].temperatureMax

 let tempMin =[0].temperatureMin

 let summary =[0].summary

 content = summary + " High: " + Math.ceil(tempMax) + " Low: " + Math.ceil(tempMin)


 catch (err) {

 console.log("couldnt get weather summary: " + err)


 return state.merge(Map({

 'weatherSummary': content


Alright, at this point you may be wondering “This is great and all, but where’s the part where we actually query the API?” Excellent question! That’s next.

Now that we have our request and receive actions setup, lets combine them in the fetchWeather action, which if you recall, is what is getting called from the WeatherDatePicker onChange event:

export function fetchWeather(weatherDate, currentLat, currentLong) {

 let request_url = ""

 let weather_str = weatherDate.format("YYYY-MM-DD") + "T00:00:00"

 request_url = request_url + currentLat + "," + currentLong + "," + weather_str

 return function (dispatch) {


 return fetch(request_url)

 .then(response => response.json())

 .catch(error => {

 console.log("unable to get weather " + error)


 .then(respData => {

 dispatch(recvWeather(weatherDate, respData))


 .catch(error => {

 console.log("unable to parse weather result " + error)




Stepping through this piece by piece – first we are constructing the URL for the DarkSky request. As explained in the Redux article, this is where the thunk middleware comes into play; this is what allows the fetchWeather action to return a function instead of an object.

The first thing the returned function from fetchWeather does is dispatch the reqWeather action to update the UI showing that we are requesting the weather. It then fetches the response from the DarkSky API, dispatching the recvWeather action if it receives a valid result.

Now, we have all the plumbing hooked up to retrieve the weather based on the date chosen in the date picker. Give it a try and download the code. If you want to make updates and deploy your own Heroku app make sure to link the create-react-app buildpack in Settings.

Some next steps to try:

  • Allow the user to get customized forecasts for each campground by modifying the CampListItem component to fetch the weather, as opposed to retrieving a general area forecast as we did in this post.
  • When querying the DarkSky API instead of just getting a daily forecast, look for a week before and a week after and get an average, high, and low temp to give a better idea of seasonal weather patterns

This year marks the 100th anniversary of the National Park Service, an organization established by Congress for “preserving the ecological and historical integrity of the places entrusted to its management while also making them available and accessible for public use and enjoyment”. Among the centennial festivities is a call to get out to experience the National Parks and “Find Your Park.”

We thought it might be fun to help you plan a National Park visit with this React app that provides current forecast information for the National Parks.

See the Pen National Park Weather with React by Sev (@sevleonard) on CodePen.

In this post we will use the Google Maps API, the DarkSky API for weather forecasting, and the Recreation Information Database (RIDB) for National Parks info. We’ll wrap all this up in a React app to help you plan a National Parks trip. For more info on getting started with RIDB and Google Maps check out Interactive Mapping with Python, GeoJSON, and JavaScript and Advanced Google Maps with JavaScript. If you are coming to React from a background in jQuery this primer is a great way to get started.

In this post you will learn:

  • Some quick Python data wrangling to acquire, clean, and organize data from an API
  • How to create a Google Maps object in React, import markers from JSON, and update info windows
  • Using state properties to optimize forecast retrieval
  • Using axiom to load external data in React
  • Using Promises to encapsulate calls to the DarkSky API
  • Dealing with CORS issues in codepen

We’re covering a lot of ground in this post, so if you’re here for something specifc you might want to skip to that area:

Using Python to get National Park Data
Setting up Google Maps in React
Integrating the DarkSky API
Async Marker Retrieval
Forecast Promises
Getting the forecast: state or API?

Getting Information on National Parks

Using the RIDB organizations endpoint we can get a list of all properties managed by the National Park Service. We’ll use a bit of Python to get this info from the API and store it into a flat file for use by our React app later on. You will need to get a RIDB API key to execute this code.

endpoint = '{orgID}/recareas'
# NPS is org_id 128
org_id = 128

params = dict(apiKey= config.RIDB_API_KEY, offset=offset)
nps_url = endpoint.replace('{orgID}', str(org_id))
resp = requests.get(url=nps_url, params=params)
data = json.loads(resp.text)
df = json_normalize(data['RECDATA'])

The RIDB endpoint will return 50 records at a time. To see how many records there are for the NPS org, we can look at the TOTAL_RECORDS field in the response data:

max_records = data['METADATA']['RESULTS']['TOTAL_COUNT']

Max records is 590. There are 58 National Parks, so clearly we are getting a lot more information than we need. We’ll extract the National Parks after we download the entire list.

We’ll continue calling the API until we’ve reached max_records, adding the response data to a data frame to accumulate all the organizations. We will use the offset value to keep track of where we are in the list and update the API query to provide the next 50 records

#save the first 50 records before we iterate

df_nps = df

while offset < max_records: offset = offset + len(df) print("offset: " + str(offset)) df = pd.DataFrame() params = dict(apiKey = config.RIDB_API_KEY, offset = offset) try: resp = requests.get(url = nps_url, params = params) except Exception as ex: print(ex) break
if resp.status_code == 200: data = json.loads(resp.text) if data['METADATA']['RESULTS']['CURRENT_COUNT'] > 0:
df = json_normalize(data['RECDATA'])
df_nps = df_nps.append(df)
else :
print("Response: " + str(resp.status_code))

Now lets look for the National Parks among this list. Lets start out by just checking the name for “National Park”

df_np = df_nps[df_nps['RecAreaName'].apply(lambda x: x.find('National Park') > 0)]

That certainly helped! Looks like we have a few extras above the 58 National Parks we have to weed out. Another thing to check for is latitude and longitude values, since we want to plot this data on a map. Lets see how many of these 61 areas are missing location info:

df_np[df_np['RecAreaLongitude'] == ""].RecAreaName
21 Arches National Park
38 Black Canyon Of The Gunnison National Park
18 Carlsbad Caverns National Park
47 Denali National Park & Preserve
43 Gates Of The Arctic National Park & Preserve
49 Glacier National Park
16 Guadalupe Mountains National Park
21 Haleakalā National Park
43 Katmai National Park & Preserve
9 Lassen Volcanic National Park
21 Western Arctic National Parklands
9 Congaree National Park Wilderness
48 Rocky Mountain National Park Wilderness

13 of the National Park areas are missing location info. Looking at the last three in the list, Western Arctic National Parklands, Congaree National Park Wilderness, and Rocky Mountain National Park Wilderness are not part of the 58 National Parks, so we will drop them from the list. For the other 10 we can look up the latitude/longitude and update the data frame with those missing values using pandas update:

# file we stored the missing lat/long values in after looking them up
missing_latlongs = pd.read_csv('missing_lat_longs.csv')
RecAreaName RecAreaLatitude RecAreaLongitude
0 Arches National Park 38.7331 -109.5925
1 Black Canyon Of The Gunnison National Park 38.5754 -107.7416
2 Carlsbad Caverns National Park 32.1479 -104.5567
3 Denali National Park & Preserve 63.1148 -151.1926
4 Gates Of The Arctic National Park & Preserve 67.9204 -153.2753

#set the indexes for missing_latlongs and df_np to the RecAreaName. The update function uses the index to merge the data
missing_latlongs = missing_latlongs.set_index('RecAreaName')
df_np = df_np.set_index('RecAreaName')

# RecAreaName has been converted to an index, recreate this field and reset the index
df_np['RecAreaName'] = df_np.index
df_np['newIndex'] = range(0,58)
df_np = df_np.drop('newIndex', axis=1)

# check that we captured all 58 National Parks
(58, 18)

#save to csv for later use

Great! We now have all 58 National Parks and their lat/long data for the map. Next lets switch over to React to create the Google Maps object for displaying these parks.

Creating the Google Maps object

While we are able to use the Google Maps API with React, it doesn’t exactly let us do so in a way that is truly React-ish, you can read more about that issue here. That caveat aside, lets dive into creating a map in React.

We’ll start by creating a React Component object to encapsulate the methods, states, and properties for the map

class NpsForecastMap extends React.Component 

The Component class includes a number of lifecycle methods to handle creation, initialization, interaction, and disposal. Lets get started by defining some properties

  state = { 

  propTypes = {
    np_url: React.PropTypes.string,
    init_lat: React.PropTypes.number,
    init_lng: React.PropTypes.number

Our app is going to generate the current forecast for each National Park when a user clicks on the marker. Since the DarkSky API isn’t free, we can keep track of if the forecast has been fetched already to avoid the overhead, both financially and in waiting on the API response, by maintaining a dictionary of forecast state. We’ll see later how this will be used to cache the current forecast.

The propTypes objects enables us to validate the inputs to our component. By parameterizing the input geojson file and the initial map center we can reuse this component with other datasets, for example, local state parks or a set of points you plan to visit on a road trip. The React.PropTypes validators enable us to confirm that the inputs received are of the expected type, though note that these validators will not screen for a valid geojson file or valid latitude and longitude, they simply check the type of the object passed.

Now that we have setup the component properties, lets take a look at some of the methods for our NpsForecastMap component.

The render() method is required, and will read the state and props properties of the component. This method will also contain the HTML representation of our component to be added to the DOM at the time of rendering. For the NpsForecastMap component will simply add a div for React to reference when building the map, as we will see later:

render() {


Remember from previous articles that we need to give the map divs a defined size:

.NpsForecastMap {
height: 100%;
position: absolute;
width: 100%;

In the HTML we have a div available for React to render the component in:

<div id="container"></div>

At the end of our React App file, we will attach the Map component to the div “container”.

ReactDOM.render(, document.getElementById('container'));

After the NpsForecastMap component has been rendered we can initialize the Google Maps object in the ComponentDidMount method, which runs after the initial rendering has occurred:

componentDidMount() { = this.createMap()
createMap() {
    let mapOptions = {
      zoom: 3,
      center: this.mapCenter()
    return new google.maps.Map(this.refs.mapdiv, mapOptions)

mapCenter() {
    return new google.maps.LatLng(

Notice that we are creating the map by referencing the mapdiv ref we created in the render() method. By providing references to entities with in the NpsForecastMap component we can avoid having to directly reference the DOM.

Async Marker Retrieval

In React apps, we want to leave the DOM rendering to React as much as possible, meaning JQuery’s methods of direct DOM manipulation don’t play nice with the React paradigm. For async calls to APIs, we can use the axios promise-based HTTP client in place of AJAX. Lets take a look at how to do that for loading the National Park geojson file.

After creating the map in the componentDidMount method, we will call a method to load the geojson and create the makers for the map.

componentDidMount() { = this.createMap()

Taking a look at the first part of the loadFeatures function, we can see how similar the axios API is to JQuery for getting data:

  loadFeatures() {
    var self = this
        .then(function(result) {   

Notice that we are saving the context ‘this’ off to a local variable ‘self’. When working with async calls its important to remember that we will be operating in a different scope when the callback occurs, so ‘this’ will pertain to that local scope, not the scope in which we called loadFeatures. Creating a variable to encapsulate the initial scope will enable us to refer to methods and properties of the class when handling the result from the async call.

When we get the result from the axios get call, we’ll iterate through each feature in the collection and create the markers:

        .then(function(result) {   
           for (let val of {
             let marker = self.createMarker(val,

Notice that we are using the ‘self’ variable to access the createMarker method of the NpsForecastMap component and to pass the map object to createMarker.

  createMarker(val, map) {
     let pointval = new google.maps.LatLng(
     let titleText = val['properties']['title']       
     let marker = new google.maps.Marker({
       position: pointval,
       map: map,
       title: titleText
    return marker

Once we parse the geojson we can create a new Marker object with the features, using the ‘map’ parameter to link the marker to the NpsForecastMap property. Now the marker will display on the map. We’ll come back to the markers to add an InfoWindow with the park name and current weather, for now lets take a look at how to get our forecast from DarkSky

See the Pen National Park Weather with React by Sev (@sevleonard) on CodePen.

Integrating the DarkSky API

Ideally, we would separate out the call to the forecast into a separate react component, ForecastAction.js for example. This would enable us to be flexible with our forecast provider, and provide a more appropriate separation of view and control in our app. We’ve started that work by creating a function with a fairly universal interface, taking only latitude and longitude as parameters and returning the current weather:

getForecast(lat, lng) {
    let request_url=""

    request_url = request_url +  lat + "," + lng 
        .then(function(result) {
            let content =

To access the DarkSky API from codepen, we need to use to avoid CORS issues when querying the forecast. To do this we prepend to the DarkSky API URL. Using the axios library again we query the API for our location and extract the daily summary, which will look something like:

“Mixed precipitation throughout the week, with temperatures peaking at 55°F on Saturday.”

So we have our forecast, but we have an async call within getForecast. We want to add the daily summary text to our marker info window, which needs to happen after we have retrieved the forecast. One option would be to pass the marker info window into the getForecast function, so we could directly update the info window when we get the forecast. But then we are mixing view elements with control elements, and making the call to getForecast less generic to enable swapping in a different forecast provider. Instead, we can wrap getForecast in a Promise, preserving the separation of control from view and maintaining the generic interface of the function.

Forecast Promises

Appropriate, since a forecast is kind of like a promise about the weather, your mileage may vary as to how well weather promises are kept, however.

If you are new to Promises here is an overview of the Promise object and how it works. At a high level, we will be creating a structure within the getForecast function that will enable us to call it like the axios get function, i.e.

    .then(function(result) {
        // add forecast to info window

First, we need to create a promise object, forecast_p. The forecast object needs to implement a resolve directive, for providing direction on when the async method has completed successfully, and a reject method for when things don’t turn out as we expect. In this promise, we only have a resolve directive for brevity.

 getForecast(lat, lng) {
    let forecast_p = new Promise(
      function(resolve,reject) {
          .then(function(result) {
            let content =

After we get the forecast from DarkSky we resolve with the daily summary.

With the Promise created, we can now determine what to do after the forecast has been fetched:

      function(result) {
        return result

return forecast_p

The result will be the daily forecast we passed to resolve() when creating the Promise. At this point, we return the Promise so the caller can determine when to initiate the DarkSky request.

Getting the forecast: state or API?

Now that we have a mechanism for getting the forecast, we can proceed with adding a click handler to the marker. In addition to getting the current forecast (or not, depending on the state) we will pop up an InfoWindow to display the park name and forecast summary. On click, we will close the current InfoWindow, this will avoid multiple InfoWindows being created and requiring the user to manually close them. We are also creating a local variable getWeather which will be used to determine if we can read from our forecast state property or if we need to query DarkSky.

let marker = th.createMarker(val,
marker.addListener('click', function() {
    let title = this.title
    let infoContent = ""
    let getWeather = false-

Now, lets check our forecast state to see if we already have the weather for this marker:

// check to see if we already have the forecast for this marker
if (title in th.state.forecast) {
    infoContent = title + "
" + th.state.forecast[title]  
else  {
    infoContent = title + "
Loading Current Weather..."
    getWeather = true

Our forecast state property is indexed by park name, which is the marker title. If we can find the park in the forecast state property we can read the forecast directly from there without having the query the API. We can create the info window content directly from here.

Otherwise, we will provide a message ‘Loading current weather’ and set our getWeather variable. Based on this, we can call into our getForecast Promise, updating the info window with the result:

if (getWeather) {
    .then(function(result) {
        infoWindow.setContent(title + "
" + result)
        th.state.forecast[title] = result

Check it out for yourself! There are some debug messages you can check out in the console to verify if the weather is being read from state

See the Pen National Park Weather with React by Sev (@sevleonard) on CodePen.


Wow, we’ve covered a lot here. Pat yourself on the back and check out this React google maps module if you’d like to take a shortcut. Tom does a great job of React-ifying the Google Maps API in this npm module.

When you’re ready for more, consider these potential next steps

  • Add an option for the user to specify a date range to check the weather for. DarkSky has a nice historical API you can use to help plan trips ahead of time
  • Separate out the forecast and maps elements into different components for better MVC separation. Check out Tom’s repo to see how he handles references to the map object for the Marker component.
  • Instead of using Python, create another React component for getting and cleaning the National Parks data, which you can then pass as a property to the NpsForecastMap component.