Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Redux with reduced boilerplate

Note

I would recommend @acdlite's redux-actions over the methods suggested in this Gist.

The methods below can break hot-reloading and don't support Promise-based actions.

Even though 'redux-actions' still uses constants, I've come to terms with the fact that constants can be good, especially in bigger projects. You can reduce boilerplate in different places, as described in the redux docs here: http://gaearon.github.io/redux/docs/recipes/ReducingBoilerplate.html


Redux is super lightweight...so it may be useful to add some helper utils on top of it to reduce some boilerplate. The goal of Redux is to keep these things in user-land, and so most likely these helpers (or anything like them) wouldn't make it into core.

It's important to note that this is just ONE (and not particularly thoroughly tested) way to accomplish the goal of reducing boilerplate in Redux. It borrows some ideas from Flummox and the way it generates action creator constants.

This will evolve, I'm sure, as time goes on and as Redux's API changes.

Some helper functions to reduce some boilerplate in Redux:

import _ from 'lodash';
import uniqueId from 'uniqueid';

// Create actions that don't need constants :)
export const createActions = (actionObj) => {
  const baseId = uniqueId();
  return _.zipObject(_.map(actionObj, (actionCreator, key) => {
    const actionId = `${baseId}-${key}`;
    const method = (...args) => {
      const result = actionCreator(...args);
      return {
        type: actionId,
        ...(result || {})
      };
    };
    method._id = actionId;
    return [key, method];
  }));
};

// Get action ids from actions created with `createActions`
export const getActionIds = (actionCreators) => {
  return _.mapValues(actionCreators, (value, key) => {
    return value._id;
  });
};

// Replace switch statements in stores (taken from the Redux README)
export const createStore = (initialState, handlers) => {
  return (state = initialState, action) =>
    handlers[action.type] ?
      handlers[action.type](state, action) :
      state;
};

They can be used like this:

Actions

import {createActions} from 'lib/utils/redux';

export const SocialPostActions = createActions({
  loadPosts(posts) {
    return { posts };
  }
});

Stores

import {default as Immutable, Map, List} from 'immutable';
import {createStore, getActionIds} from 'lib/utils/redux';

import {SocialPostActions} from 'lib/actions';

const initialState = Map({
  isLoaded: false,
  posts: List()
});

const actions = getActionIds(SocialPostActions);

export const posts = createStore(initialState, {
  [actions.loadPosts]: (state, action) => {
    return state.withMutations(s =>
      s.set('isLoaded', true).set('posts', Immutable.fromJS(action.posts))
    );
  }
});

vjpr commented Jun 18, 2015

Doesn't seem to work for async actions that return a function.

vjpr commented Jun 18, 2015

It's because it turns all actions in objects. The thunkMiddleware checks the type of the action, and runs async if its a function.

// src/middleware/thunk.js

export default function thunkMiddleware(getState) {
  return (next) => {
    const recurse = (action) =>
      typeof action === 'function' ?
        action(recurse, getState) :
        next(action);

    return recurse;
  };
}

vjpr commented Jun 18, 2015

To use with the existing example you must access the methods on the hash like this: CounterActions.increment(). Here's the full example again.

export const CounterActions = createActions({

  increment() {
    return {}
  },

  incrementIfOdd() {
    return (dispatch, getState) => {
      const {counter} = getState()
      console.log(dispatch)
      if (counter % 2 === 0) return
      dispatch(CounterActions.increment())
    }
  },

  incrementAsync() {
    return dispatch => {
      setTimeout(() => {
        dispatch(CounterActions.increment())
      }, 1000)
    }
  },

  decrement() {
    return {}
  },

})

vjpr commented Jun 18, 2015

The following fixes the async issue, by checking if its a function and wrapping it.

// Create actions that don't need constants :)
export const createActions = (actionObj) => {
  const baseId = uniqueId();
  return _.zipObject(_.map(actionObj, (actionCreator, key) => {
    const actionId = `${baseId}-${key}`;
    const method = (...args) => {
      const result = actionCreator(...args);
      if (typeof result === 'function') {
        return (...args) => {
          return {
            type: actionId,
            ...(result(...args) || {})
          };
        }
      } else {
        return {
          type: actionId,
          ...(result || {})
        };
      }
    };
    method._id = actionId;
    return [key, method];
  }));
};

vjpr commented Jun 18, 2015

I really liked Flummox's action class with ES7 async support. We should port that, and turn it into an npm lib. Just needs some custom middleware from here: gaearon/redux#99 (comment) and a bit of sugar.

vjpr commented Jun 19, 2015

To use promises replace const redux = createRedux(stores) with the following:

import {createRedux, createDispatcher, composeStores} from 'redux';
import thunkMiddleware from 'redux/lib/middleware/thunk';
import {compose} from 'redux';
import * as stores from '../stores/index'; // Your stores.

export function promiseMiddleware() {
  return (next) => (action) => {
    const { promise, types, ...rest } = action;
    if (!promise) {
      return next(action);
    }

    const [REQUEST, SUCCESS, FAILURE] = types;
    next({ ...rest, type: REQUEST });
    return promise.then(
      (result) => next({ ...rest, result, type: SUCCESS }),
      (error) => next({ ...rest, error, type: FAILURE })
    );
  };
}

const store = composeStores(stores);

const dispatcher = createDispatcher(
  store,
  getState => [promiseMiddleware(), thunkMiddleware(getState)]
);

const redux = createRedux(dispatcher);

Usage (adapted from README example):

  incrementIfOdd() {

    // Debug
    const promise = new Promise( (resolve, reject) => {
      setTimeout(() => {
        resolve()
      }, 1000)
    })

    return {
      types: ['INCREMENT_BEGIN', 'INCREMENT_SUCCESS', 'INCREMENT_FAILURE'],
      promise,
    }

  },

vjpr commented Jun 19, 2015

Here is a new createActions that supports promises, functions and objects. Probably should be a new gist by now...

// redux-helpers.js

import _ from 'lodash';
import uniqueId from 'uniqueid';

// Create actions that don't need constants :)
export const createActions = (actionObj) => {
  const baseId = uniqueId();
  return _.zipObject(_.map(actionObj, (actionCreator, key) => {
    const actionId = `${baseId}-${key}`;
    const method = (...args) => {
      const result = actionCreator(...args);

      if (result instanceof Promise) {
        // Promise (async)
        return {
          types: ['BEGIN', 'SUCCESS', 'FAILURE'].map( (state) => `${actionId}-${state}`),
          promise: result,
        }
      } else if (typeof result === 'function') {
        // Function (async)
        return (...args) => {
          return {
            type: actionId,
            ...(result(...args) || {})
          };
        }
      } else {
        // Object (sync)
        return {
          type: actionId,
          ...(result || {})
        };
      }
    };
    method._id = actionId;
    return [key, method];
  }));
};

// Get action ids from actions created with `createActions`
export const getActionIds = (actionCreators) => {
  return _.mapValues(actionCreators, (value, key) => {
    return value._id;
  });
};

// Replace switch statements in stores (taken from the Redux README)
export const createStore = (initialState, handlers) => {
  return (state = initialState, action) =>
    handlers[action.type] ?
      handlers[action.type](state, action) :
      state;
};

export function promiseMiddleware() {
  return (next) => (action) => {
    const { promise, types, ...rest } = action;
    if (!promise) {
      return next(action);
    }

    const [REQUEST, SUCCESS, FAILURE] = types;
    next({ ...rest, type: REQUEST });
    return promise.then(
      (result) => next({ ...rest, result, type: SUCCESS }),
      (error) => next({ ...rest, error, type: FAILURE })
    );
  };
}

Usage

export const CounterActions = createActions({

  increment() {

    // Debug
    const promise = new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve()
      }, 1000)
    })

    return promise

  },

  // ...or with ES7 async awesomeness (a la Flummox ;)
  async increment() {

    // Debug
    const promise = new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve()
      }, 1000)
    })

    let result = await promise
    return result

  },

}
import {createStore, getActionIds} from 'redux-helpers'
import {default as Immutable, Map, List} from 'immutable'

import {CounterActions} from '../actions'

const actions = getActionIds(CounterActions)

const initialState = 0

export const counter = createStore(initialState, {

  [actions.increment+'-SUCCESS']: (state, actions) => {
    return state + 5
  },

})

how about distributing this under addons like React does?

faassen commented Jun 25, 2015

I think 'addons' has the wrong implications. Either make this a full part of Redux itself and maintain it as such, or distribute it as its own package entirely. See also how the React devs in fact want to get rid of addons into separately maintained packages.

faassen commented Jun 25, 2015

Anyway, to get started I think it would make sense to put this code (and the worked out example in the other gist) in a git repo. @vjpr, do you need help with this? I'd also like to help out writing tests if needed.

Owner

skevy commented Jun 29, 2015

Not sure why I wasn't notified on comments on this.

@vjpr thanks for your examples. I had run into this problem of it not supporting promises as well...and I ended up with something similar to what you did.

cassus commented Jul 5, 2015

It would be great to have this on npm, also maybe under the redux github org.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment