This is the first part in a series of tutorials showing how to convert Flux code to Redux.

I find it easiest to start by converting actions from a standard Flux action into a Redux action. This allows you to start at one thread of your application and work your way through a specific stack.

Converting action creators

Below is our flux action. It contains a single method that calls out to a XHR-based service. Thre result from this service dispatches the corresponding action.

let dispatcher  = require('dispatcher');
let userService = require('services/user-service');
let { FLASH, USERS_LOADED } = require('constants/action-types');

module.exports = {

  /**
   * Gets the user with the supplied paging and filtering info
   * @param {object} opts
   */
  async getUsers(opts) {
    let results = await userService.getUsers(opts);
    if(results.success) {
      dispatcher.dispatch({
        type: USERS_LOADED,
        payload: {
          users: results.body,
          paging: results.paging
        }
      });
    } 
    else {
      dispatcher.dispatch({
        type: FLASH,
        payload: {
          flash: {
            type: 'error',
            message: results.error
          }
        }
      });
    }    
  }
};

The implementation of the service is irrelevant. Both Flux action creators and Redux action creators can use the service. If you're curious though, I use react-service-utils to create a uniform response from all of my XHR based services.

To convert this action creator into a Redux action creator is straightforward. We need to remove the dispatch plumbing and directly return an object.

import userService from 'services/user-service';
import { FLASH, USERS_LOADED } from 'constants/action-types';

export default {

  /**
   * Gets the user with the supplied paging and filtering info
   * @param {object} opts
   */
  async getUsers(opts) {
    let results = await userService.getUsers(opts);
    if(results.success) {
      return {
        type: USERS_LOADED,
        users: results.body,
        paging: results.paging
      };
    }
    else {
      return {
        type: FLASH,
        flash: {
          type: 'error',
          message: results.error
        }
      };
    }    
  }
};

As you can see, Redux actions are actually just simpler versions of our Flux action creators.