We're live-coding on Twitch! Join us!
Build A Media Library With React, Redux, and Redux-saga - Part 2

Build A Media Library With React, Redux, and Redux-saga - Part 2

In the first part of this tutorial, we had a running app. We covered basic React setup, project workflow; defined basic components and configured our application's routes.

In Part 2 of this tutorial, which is unarguably the most interesting part of building React/Redux application, we will setup application state management with redux, connect our React components to the store, and then deploy to Heroku. We will walk through this part in eight steps:

  1. Define Endpoints of interest.
  2. Create a container component.
  3. Define action creators.
  4. Setup state management system.
  5. Define async task handlers.
  6. Create presentational components.
  7. Connect our React component to Redux store.
  8. Deploy to Heroku.

Step 1 of 8: Define Endpoints of interest

Our interest is the media search endpoints of Flickr API and Shutterstock API.


const FLICKR_API_KEY = 'a46a979f39c49975dbdd23b378e6d3d5';
const SHUTTER_CLIENT_ID = '3434a56d8702085b9226';
const SHUTTER_CLIENT_SECRET = '7698001661a2b347c2017dfd50aebb2519eda578';

// Basic Authentication for accessing Shutterstock API
const basicAuth = () => 'Basic '.concat(window.btoa(`${SHUTTER_CLIENT_ID}:${SHUTTER_CLIENT_SECRET}`));
const authParameters = {
  headers: {
    Authorization: basicAuth()

* Description [Access Shutterstock search endpoint for short videos]
* @params { String } searchQuery
* @return { Array } 
export const shutterStockVideos = (searchQuery) => {
  const SHUTTERSTOCK_API_ENDPOINT = `https://api.shutterstock.com/v2/videos/search?

  return fetch(SHUTTERSTOCK_API_ENDPOINT, authParameters)
  .then(response => {
    return response.json();
  .then(json => {
      return json.data.map(({ id, assets, description }) => ({
        mediaUrl: assets.preview_mp4.url,

* Description [Access Flickr search endpoint for photos]
* @params { String } searchQuery
* @return { Array } 
export const flickrImages = (searchQuery) => {
  const FLICKR_API_ENDPOINT = `https://api.flickr.com/services/rest/?method=flickr.photos.search&text=${searchQuery}&api_key=${FLICKR_API_KEY}&format=json&nojsoncallback=1&per_page=10`;

  return fetch(FLICKR_API_ENDPOINT)
    .then(response => {
      return response.json()
    .then(json => {
      return json.photos.photo.map(({ farm, server, id, secret, title }) => ({
        mediaUrl: `https://farm${farm}.staticflickr.com/${server}/${id}_${secret}.jpg`

First, head to Flickr and Shutterstock to get your credentials or use mine.

We’re using fetch method *from *fetch API for our AJAX request. It returns a promise that resolves to the response of such request. We simply format the response of our call using ES6 destructuring assignment before returning to the store.

We can use jQuery for this task but it’s such a large library with many features, so using it just for AJAX doesn’t make sense.

Step 2 of 8: Create a container component

In order to test our application as we walk through the steps, let's define a MediaGalleryPage component which we will update later for a real time sync with our store.


BeginnerWebDev.com Get Started w/ JavaScript for free!
import React, { Component } from 'react';
import { flickrImages, shutterStockVideos } from '../Api/api';

// MediaGalleryPage Component
class MediaGalleryPage extends Component {

 // We want to get images and videos from the API right after our component renders.
 componentDidMount() {
    flickrImages('rain').then(images => console.log(images, 'Images'));
    shutterStockVideos('rain').then(videos => console.log(videos,'Videos'));

  render() {
  // TODO: Render videos and images here
  return (<div></div>)

export default MediaGalleryPage;

We can now add library route and map it to MediaGalleryPage Container.

Let's update out routes.js for this feature.

import React from 'react';
import { Route, IndexRoute } from 'react-router';
import App from './containers/App';
import HomePage from './components/HomePage';
import MediaGalleryPage from './containers/MediaGalleryPage';

// Map components to different routes.
// The parent component wraps other components and thus serves as 
// the entrance to other React components.
// IndexRoute maps HomePage component to the default route
export default (
  <Route path="/" component={App}>
    <IndexRoute component={HomePage} />
    <Route path="library" component={MediaGalleryPage} />

Let's check it out on the browser console.

Images and Videos from the API

We are now certain that we can access our endpoints of interest to fetch images and short videos. We can render the results to the view but we want to separate our React components from our state management system. Some major advantages of this approach are maintainability, readability, predictability, and testability.

We will be wrapping our heads around some vital concepts in a couple of steps.

Step 3 of 8: Define action creators

Action creators are functions that return plain Javascript object of action type and an optional payload. So action creators create actions that are dispatched to the store. They are just pure functions.

Let’s first define our action types in a file and export them for ease of use in other files. They’re constants and it’s a good practice to define them in a separate file(s).


// It's preferable to keep your action types together.

Now, we can use the action types to define our action creators for different actions we need.


import * as types from '../constants/actionTypes';

// Returns an action type, SELECTED_IMAGE and the image selected
export const selectImageAction = (image) => ({
  type: types.SELECTED_IMAGE,

// Returns an action type, SELECTED_VIDEO and the video selected
export const selectVideoAction = (video) => ({
  type: types.SELECTED_VIDEO,

// Returns an action type, SEARCH_MEDIA_REQUEST and the search criteria
export const searchMediaAction = (payload) => ({

The optional arguments in the action creators: payload, image, and video are passed at the site of call/dispatch. Say, a user selects a video clip on our app, selectVideoAction is dispatched which returns SELECTED_VIDEO action type and the selected video as payload. Similarly, when searchMediaAction is dispatched, SEARCH_MEDIA_REQUEST action type and payload are returned.

Step 4 of 8: Setup state management system

We have defined the action creators we need and it's time to connect them together. We will setup our reducers and configure our store in this step.

There are some wonderful concepts here as shown in the diagram in Part 1.

Let's delve into some definitions and implementations.

The Store holds the whole state tree of our application but more importantly, it does nothing to it. When an action is dispatched from a React component, it delegates the reducer but passing the current state tree alongside the action object. It only updates its state after the reducer returns a new state.

*Reducers, for short are pure functions that accept the state tree and an action object from the store and returns a new state. No state mutation. No API calls. No side effects. It simply calculates the new state and returns it to the store.*

Let’s wire up our reducers by first setting our initial state. We want to initialize images and videos as an empty array in our own case.


export default {
  images: [],
  videos: []

Our reducers take the current state tree and an action object and then evaluate and return the outcome.

Let’s check it out.


import initialState from './initialState';
import * as types from '../constants/actionTypes';

// Handles image related actions
export default function (state = initialState.images, action) {
  switch (action.type) {
      return [...state, action.images];
    case types.SELECTED_IMAGE:
      return { ...state, selectedImage: action.image };
      return state;


import initialState from './initialState';
import * as types from '../constants/actionTypes';

// Handles video related actions
// The idea is to return an updated copy of the state depending on the action type.
export default function (state = initialState.videos, action) {
  switch (action.type) {
      return [...state, action.videos];
    case types.SELECTED_VIDEO:
      return { ...state, selectedVideo: action.video };
      return state;

The two reducers look alike and that’s how simple reducers can be. We use a switch statement to evaluate an action type and then return a new state.

create-react-app comes preinstalled with *babel-plugin-transform-object-rest-spread* that lets you use the spread (…) operator to copy enumerable properties from one object to another in a succinct way.

For context, { …state, videos: action.videos } evaluates to Object.assign({}, state, action.videos).

Since reducers don’t mutate state, you would always find yourself using spread operator, to make and update the new copy of the current state tree.

So, When the reducer receives SELECTED_VIDEO action type, it returns a new copy of the state tree by spreading it(…state) and updating the selectedVideo property.

The next step is to register our reducers to a root reducer before passing to the store.


import { combineReducers } from 'redux';
import images from './imageReducer';
import videos from './videoReducer';

// Combines all reducers to a single reducer function
const rootReducer = combineReducers({

export default rootReducer;

We import combineReducers from Redux. CombineReducers is a helper function that combines our images and videos reducers into a single reducer function that we can now pass to the creatorStore function.

You might be wondering why we’re not passing in key/value pairs to combineReducers function. Yes, you’re right. ES6 allows us to pass in just the property if the key and value are the same.

Now, we can complete our state management system by creating the store for our app.


import { createStore, applyMiddleware } from 'redux';
import createSagaMiddleware from 'redux-saga';
import rootReducer from '../reducers';
import rootSaga from '../sagas'; // TODO: Next step

//  Returns the store instance
// It can  also take initialState argument when provided
const configureStore = () => {
  const sagaMiddleware = createSagaMiddleware(); 
  return {
    runSaga: sagaMiddleware.run(rootSaga)

export default configureStore;
  • Initialize your SagaMiddleWare. We’d discuss about sagas in the next step.
  • Pass rootReducer and sagaMiddleware to the createStore function to create our redux store.
  • Finally, we run our sagas. You can either spread them or wire them up to a rootSaga.

What are sagas and why use a middleware?

Step 5 of 8: Define async task handlers

Handling AJAX is a very important aspect of building web applications and React/Redux application is not an exception. We will look at the libraries to leverage for such task and how they neatly fit into the whole idea of having a state management system.

You would remember reducers are pure functions and don’t handle side effects or async tasks; this is where redux-saga comes in handy.

*redux-saga is a library that aims to make side effects (i.e. asynchronous things like data fetching and impure things like accessing the browser cache) in React/Redux applications easier and better — documentation.*

So, to use redux-saga, we also need to define our own sagas that will handle the necessary async tasks.

What the heck are sagas?

Sagas are simply generator functions that abstract the complexities of an asynchronous workflow. It’s a terse way of handling async processes. It’s easy to write, test and reason. Still confused, you might want to revisit the first part of this tutorial if you missed it.

Let’s first define our watcher saga and work down smoothly.


import { takeLatest } from 'redux-saga/effects';
import { searchMediaSaga } from './mediaSaga';
import * as types from '../constants/actionTypes';

// Watches for SEARCH_MEDIA_REQUEST action type asynchronously
export default function* watchSearchMedia() {
  yield takeLatest(types.SEARCH_MEDIA_REQUEST, searchMediaSaga);

We want a mechanism that ensures any action dispatched to the store which requires making API call is intercepted by the middleware and result of request yielded to the reducer.

To achieve this, Redux-saga API exposes some methods. We need only four of those for our app: call, put, fork and takeLatest.

  • takeLatest is a high-level method that merges take and fork effect creators together. It basically takes an action type and runs the function passed to it in a non-blocking manner with the result of the action creator. As the name suggests, takeLatest returns the result of the last call.
  • watchSearchMedia watches for SEARCH_MEDIA_REQUEST action type and call searchMediaSaga function(saga) with the action’s payload from the action creator.

Now, we can define searchMediaSaga; it serves as a middleman to call our API. Getting interesting right?


import { put, call } from 'redux-saga/effects';
import { flickrImages, shutterStockVideos } from '../Api/api';
import * as types from '../constants/actionTypes';

// Responsible for searching media library, making calls to the API
// and instructing the redux-saga middle ware on the next line of action,
// for success or failure operation.
export function* searchMediaSaga({ payload }) {
  try {
    const videos = yield call(shutterStockVideos, payload);
    const images = yield call(flickrImages, payload);
    yield [
      put({ type: types.SHUTTER_VIDEOS_SUCCESS, videos }),
      put({ type: types.SELECTED_VIDEO, video: videos[0] }),
      put({ type: types.FLICKR_IMAGES_SUCCESS, images }),
      put({ type: types.SELECTED_IMAGE, image: images[0] })
  } catch (error) {
    yield put({ type: 'SEARCH_MEDIA_ERROR', error });

searchMediaSaga is not entirely different from normal functions except the way it handles async tasks.

call is a redux-saga effect that instructs the middleware to run a specified function with an optional payload.

Let’s do a quick review of some happenings up there.

  • searchMediaSaga is called by the watcher saga defined earlier on each time SEARCH_MEDIA_REQUEST is dispatched to store.
  • It serves as an intermediary between the API and the reducers.

  • So, when the saga(searchMediaSaga) is called, it makes a call to the API with the payload. Then, the result of the promise(resolved or rejected) and an action object is yielded to the reducer using put effect creator. put instructs Redux-saga middleware on what action to dispatch.
  • Notice, we’re yielding an array of effects. This is because we want them to run concurrently. The default behaviour would be to pause after each yield statement which is not the behaviour we intend.
  • Finally, if any of the operations fail, we yield a failure action object to the reducer.

Let’s wrap up this section by registering our saga to the rootSaga.


import { fork } from 'redux-saga/effects';
import watchSearchMedia from './watcher';

// Here, we register our watcher saga(s) and export as a single generator 
// function (startForeman) as our root Saga.
export default function* startForman() {
  yield fork(watchSearchMedia);

fork is an effect creator that provisions the middleware to run a non-blocking call on watchSearchMedia saga.

Here, we can bundle our watcher sagas as an array and yield them at once if we have more than one.

Hope by now, you are getting comfortable with the workflow. So far, we’re able to export startForman as our rootSaga.

How does our React component know what is happening in the state management system?

Step 6 of 8: Connect our React component to redux store

I’m super excited that you’re still engaging and we’re about testing our app.

First, let’s update our index.js * app’s entry file.*

import ReactDOM from 'react-dom';
import React from 'react';
import { Router, browserHistory } from 'react-router';
import { Provider } from 'react-redux';  
import configureStore from './store/configureStore';
import routes from './routes';

// Initialize store
const store = configureStore();

  <Provider store={store}>
    <Router history={browserHistory} routes={routes} />
  </Provider>, document.getElementById('root')

Let’s review what’s going on.

  • Initialize our store.
  • Provider component from react-redux makes the store available to the components hierarchy. So, we have to pass the store as props to it. That way, the components below the hierarchy can access the store’s state with connect method call.

Now, let's update our MediaGalleryPage component to access the store.


import React, { Component } from 'react';
import { connect } from 'react-redux';
import { searchMediaAction } from '../actions/mediaActions';

// MediaGalleryPage Component
class MediaGalleryPage extends Component {

  // Dispatches *searchMediaAction*  immediately after initial rendering.
  // Note that we are using the dispatch method from the store to execute this task, courtesy of react-redux
 componentDidMount() {

  render() {
    console.log(this.props.images, 'Images');
    console.log(this.props.videos, 'Videos');
    console.log(this.props.selecteImage, 'SelectedImage');
    console.log(this.props.selectedVideo, 'SelectedVideo');
    return (<div> </div>)

// Define PropTypes
MediaGalleryPage.propTypes = {
// Define your PropTypes here

 // Subscribe component to redux store and merge the state into 
 // component's props
const mapStateToProps = ({ images, videos }) => ({
  images: images[0],
  selectedImage: images.selectedImage,
  videos: videos[0],
  selectedVideo: videos.selectedVideo

// connect method from react-router connects the component with redux store
export default connect(

MediaGalleryPage component serves two major purposes:

a) Sync React Components with the Redux store.

b) Pass props to our presentational components: PhotoPage and VideoPage. We will create this later in the tutorial to render our content to the page.

Let’s summarize what's going on.

React-redux exposes two important methods(components) we will use to bind our redux store to our component - connect and Provider.

connect takes three optional functions. If any is not defined, it takes the default implementation. It’s a function that returns a function that takes our React component-MediaGalleryPage as an argument.

mapStateToProps allows us keep in sync with store's updates and to format our state values before passing as props to the React component. We use ES6 *destructuring assignment* to extract images and videos from the store’s state.

Now, everthing is good and we can test our application.

$ npm start

You can grab a cup of coffee and be proud of yourself.

Wouldn't it be nice if we can render our result on the webpage as supposed to viewing them on the browser console?

Step 7 of 8: Create presentational components

What are presentational components?

They are basically components that are concerned with presentation - how things look. Early in this tutorial, we created a container component - MediaGalleryPage which will be concerned with passing data to these presentational components. This is a design decision which has helped large applications scale efficiently. However, it's at your discretion to choose what works for your application.

Our task is now easier. Let's create the two React components to handle images and the videos.


import React, { PropTypes } from 'react';

// First, we extract images, onHandleSelectImage, and selectedImage from 
// props using ES6 destructuring assignment and then render.
const PhotosPage = ({ images, onHandleSelectImage, selectedImage }) => (
  <div className="col-md-6">
    <h2> Images </h2>
    <div className="selected-image">
      <div key={selectedImage.id}>
        <img src={selectedImage.mediaUrl} alt={selectedImage.title} />
    <div className="image-thumbnail">
      {images.map((image, i) => (
        <div key={i} onClick={onHandleSelectImage.bind(this, image)}>
          <img src={image.mediaUrl} alt={image.title} />

// Define PropTypes
PhotosPage.propTypes = {
  images: PropTypes.array.isRequired,
  selectedImage: PropTypes.object,
  onHandleSelectImage: PropTypes.func.isRequired

export default PhotosPage;


import React, { PropTypes } from 'react';

// First, we extract videos, onHandleSelectVideo, and selectedVideo 
// from props using destructuring assignment and then render.
const VideosPage = ({ videos, onHandleSelectVideo, selectedVideo }) => (
  <div className="col-md-6">
    <h2> Videos </h2>
    <div className="select-video">
      <div key={selectedVideo.id}>
        <h6 className="title">{selectedVideo.description}</h6>
        <video controls src={selectedVideo.mediaUrl} alt={selectedVideo.title} />
    <div className="video-thumbnail">
      {videos.map((video, i) => (
        <div key={i} onClick={onHandleSelectVideo.bind(this, video)}>
          <video controls src={video.mediaUrl} alt={video.description} />

// Define PropTypes
VideosPage.propTypes = {
  videos: PropTypes.array.isRequired,
  selectedVideo: PropTypes.object.isRequired,
  onHandleSelectVideo: PropTypes.func.isRequired

export default VideosPage;

The two React components are basically the same except that one handles images and the other is responsible for rendering our videos.

Let's now update our MediaGalleryPage to pass props to this components.


import React, { PropTypes, Component } from 'react';
import { connect } from 'react-redux';
import {
  selectImageAction, searchMediaAction,
  selectVideoAction } from '../actions/mediaActions';
import PhotoPage from '../components/PhotoPage';
import VideoPage from '../components/VideoPage';
import '../styles/style.css';

// MediaGalleryPage Component
class MediaGalleryPage extends Component {
  constructor() {
    this.handleSearch = this.handleSearch.bind(this);
    this.handleSelectImage = this.handleSelectImage.bind(this);
    this.handleSelectVideo = this.handleSelectVideo.bind(this);

  // Dispatches *searchMediaAction*  immediately after initial rendering
 componentDidMount() {

  // Dispatches *selectImageAction* when any image is clicked
  handleSelectImage(selectedImage) {

  // Dispatches *selectvideoAction* when any video is clicked
  handleSelectVideo(selectedVideo) {

  // Dispatches *searchMediaAction* with query param.
  // We ensure action is dispatched to the store only if query param is provided.
  handleSearch(event) {
    if (this.query !== null) {
      this.query.value = '';

  render() {
    const { images, selectedImage, videos, selectedVideo } = this.props;
    return (
      <div className="container-fluid">
        {images && selectedImage? <div>
            ref={ref => (this.query = ref)}
       className="btn btn-primary"
            value="Search Library"
          <div className="row">
        </div> : 'loading ....'}

// Define PropTypes
MediaGalleryPage.propTypes = {
  images: PropTypes.array,
  selectedImage: PropTypes.object,
  videos: PropTypes.array,
  selectedVideo: PropTypes.object,
  dispatch: PropTypes.func.isRequired

 // Subscribe component to redux store and merge the state into component's props
const mapStateToProps = ({ images, videos }) => ({
  images: images[0],
  selectedImage: images.selectedImage,
  videos: videos[0],
  selectedVideo: videos.selectedVideo

// connect method from react-router connects the component with redux store
export default connect(

This is pretty much how our final MediaGalleryPage component looks like. We can now render our images and videos to the webpage.

Let's recap on the latest update on MediaGalleryPage component.

render method of our component is very interesting. Here we’re passing down props from the store and the component’s custom functions(handleSearch, handleSelectVideo, handleSelectImage) to the presentational components — PhotoPage and VideoPage.

This way, our presentational components are not aware of the store. They simply take their behaviour from MediaGalleryPage component and render accordingly.

Each of the custom functions dispatches an action to the store when called. We use ref to save a callback that would be executed each time a user wants to search the library.

componentDidMount Lifecycle method is meant to allow dynamic behaviour, side effects, AJAX, etc. We want to render search result for rain once a user navigates to library route.

One more thing. We bound all the custom functions in the component’s constructor function with .bind() ** method. It’s simply Javascript. **bind() allows you to create a function out of regular functions. The first argument to it is the context(this, in our own case) to which you want to bind your function. Any other argument will be passed to such function that’s bounded.

We’re done building our app. Surprised?

Let’s test it out…

$ npm start

Step 8 of 8: Deploy to Heroku

Now that our app works locally, let’s deploy to a remote server for our friends to see and give us feedback. Heroku’s free plan will suffice.

We want to use create-react-app’s build script to bundle our app for production.

$ npm run build

A build/ folder is now in our project directory. That’s the minified static files we will deploy.

Next step is to add another script command to our package.json to help us serve our build files with a static file server. We will use pushstate-server(a static file server) to serve our files.

"deploy": "npm install -g pushstate-server && pushstate-server build"

Let's create Procfile in our project's root directory and add: web: npm run deploy

Procfile instructs Heroku on how to run your application.

Now, let’s create our app on Heroku. You need to register first on their platform. Then, download and install *Heroku toolbelt * if it’s not installed on your system. This will allow us to deploy our app from our terminal.

$ heroku login # Enter your credentials as it prompts you
$ heroku create <app name> # If  you don't specify a name, Heroku creates one for you.
$ git add --all && git commit -m "Add comments"  # Add and commit your changes.
$ git push heroku master # Deploy to Heroku
$ heroku ps:scale web=1 # Initialize one instance of your app
$ heroku open # Open your app in your default browser

We did it. Congrats. You’ve built and deployed a React/Redux application elegantly. It can be that simple.

Now some recommended tasks.

  1. Add tests for your application.
  2. Add error handling functionality.
  3. Add a loading spinner for API calls for good user experience.
  4. Add sharing functionality to allow users share on their social media walls
  5. Allow users to like an image.


It’s apparent that some things were left out, some intentionally. However, you can improve the app for your learning. The key takeaway is to separate your application state from your React components. Use redux-saga to handle any AJAX requests and don’t put AJAX in your React components. Good luck!!!

Like this article? Follow @rowlandekemezie on Twitter