NASA Photo of the Day 3

Building an app that connects to a remote API to demonstrate Redux middleware

We are building an application that loads a photo from a remote API: the NASA Photo of the Day.

The application will be in one of three different states:

  • LOADING, when we start fetching the photo

  • SUCCESS, if the photo is fetched successfully

  • FAILURE, if there is an error fetching the photo.

Our action creator needs to transition to one of these states by sending the appropriate action to the reducer.

The actions sent by the action creator will be one of these three types:

  • FETCH_PHOTO_START

  • FETCH_PHOTO_SUCCESS

  • FETCH_PHOTO_FAILURE

We started our by simply sending out the FETCH_PHOTO_START action type.
We created an action creator called getPhoto that is defined in actions/index.js
This is the code we have so far:

// src/actions/index.js

export const FETCH_PHOTO_START = 'FETCH_PHOTO_START';

export const getPhoto = () => {
  return {
    type: FETCH_PHOTO_START
  }
}

Triggering the action

Now that we have an action ready we might as well pull the trigger. We want to trigger the action with a button click. So, we add an onClick event to our Fetch Photo button.

// src/components/NASAPhoto.js

<button onClick={fetchPhoto}>Fetch Photo</button>

The onClick event is associated with a function named fetchPhoto that we need to define in the NASAPhoto component:

// src/components/NASAPhoto.js

const fetchPhoto = e => {
  e.preventDefault();
  props.getPhoto();
}

fetchPhoto takes an event (our button click) as the argument. Inside of the function body, we first prevent the default browser action of reloading the page after a button click.

Next, we call the getPhoto action creator that is on the props.
One thing to note is that we haven't yet added getPhoto to the props, so we need to do it now.

To add this action creator to the props we just import the action creator file at the top of NASAPhoto.js and add the getPhoto function to the connect function at the bottom:

import { getPhoto } from '../actions';

// ... existing code ...

export default connect(
  mapStateToProps,
  { getPhoto }
)(NASAPhoto);

After these changes, if we click on the Fetch Photo button we can see our spinner being loaded. Great! We have successfully entered into the LOADING state.

Now we have to find a way to actually fetching the photo by making an API call.
Where would we handle that? Inside the action creator, of course!

We will see how to add this functionality in tomorrow's article.


Did you like this article? Share it with your friends.
I write daily about front-end and back-end web technologies.
You can receive all my articles in your inbox by subscribing to my newsletter. Just click the button below. No spam, just good, useful content. Guaranteed!


Follow me on Twitter