1.1.1 • Published 8 years ago

redux-action-class-middleware v1.1.1

Weekly downloads
8
License
MIT
Repository
github
Last release
8 years ago

Build Status

redux-action-class-middleware

Redux middleware that lets you define async/sync actions as ES6 classes.

This middleware is an alternative to the more functional variant, redux-thunk. Using redux-action-class-middleware, you can encapsulate actions as ES6 classes.

This results in less actions overall since you can add asynchronous behavior to an action that reducers see. With redux-thunk, you would have to create an equivalent synchronous action for the async action in order for reducers to change state before the async action executes.

That said, this middleware doesn't require actions to be classes. Any object with an execute() property will work. Eg,

{
    type: 'FETCH_TODOS'
    execute: function(dispatch) {
        dispatch({type: 'TODOS_RECEIVED', todos: ...});
    }
}

will work as well.

Important Note: Redux does not allow actions to be anything other than plain JavaScript objects (ie, objects w/ a class). It does this in order to be able to save copies of actions for replaying. Because of this, there are some limitations on how you can create these classes:

  1. Your action class names must be unique across your app. This middleware will create plain objects for your class objects. The action's type property is set to the class name. So if your class names are not unique, there might be collisions, resulting in strange behavior.
  2. You can't use instanceof in reducers since the actions reducers will see are not the action instances you create, but plain JS copies. Instead you must use the is function in the middleware module (see below for an example).

Example

import { is as actionIs } from 'redux-action-class-middleware'

// sync action with no extra logic
class TodosFetched {
    constructor(issues) {
        this.issues = issues
    }
}

// async action that starts an AJAX request to get the TODO entities
class FetchTodos {
    execute(dispatch) {
        API.fetchTodos().then(function (issues) {
            dispatch(new TodosFetched(issues))
        })
    }
}

let reducer = function (state, action) {
    if (actionIs(action, FetchTodos)) {
        return Object.assign({}, state, {loading: true})
    }

    if (actionIs(action, TodosFetched)) {
        return Object.assign({}, state, {issues: action.issues, loading: false})
    }

    return state
}
1.1.1

8 years ago

1.1.0

8 years ago

1.0.1

8 years ago

1.0.0

8 years ago