redux-action-trigger

0.2.3 • Public • Published

redux-action-trigger

What is this?

  1. Mark action which you want to trigger after it will be dispatched.
  2. After action has been triggered, it will be processed by your function and another action can be called.

Use-case example:

You have app where you want to do something (e.g. refresh user token) after every dispatching of certain actions (e.g. actions connected to user settings).

  1. Mark all (user settings) actions for redux-action-trigger with wrapAction()
  2. Provide processing function as argument for middleware. This function can dispatch other actions. (e.g. refresh user token function)
  3. PROFIT!!!!!

Why don't use reducer?

We can only modify app's state with reducers, but we can't dispatch action (or do stuff like request) inside reducer.

Also, your app still following concepts of purity and immutability.

Install:

npm install --save redux-action-trigger

How it works?

You can find examples here.

Add middleware

Just add redux-action-trigger to your middlewares and provide configuration:

import {trigger} from 'redux-action-trigger'
// ...
let middleware = applyMiddleware(trigger(reporting))

Add config

You see that we provide reporting as argument for the middleware.
It can be a function or an object.

Func-style:

You can provide function that will process dispatched action:

const reporting = (dispatch, dispatchedAction) => {
    dispatch(sendReportToServer(action))
}
Object-style:

Alternatively, you can pass object with processAction method.

Object is recommended way, because this middleware may have more features as more configuration in the future.

const reporting = {
    processAction(dispatch, dispatchedAction) {
        dispatch(sendReportToServer(action))
    }
}

processAction(dispatch, action)

/**
 * Process dispatched action
 * @param {Func} dispatch - store.dispatch
 * @param {Number} action - just fired action
 */

store.dispatch - might be useful for dispatching action that isn't connected to main application logic

Mark actions for being triggered by middleware

You can mark action with wrapAction():

import {wrapAction} from 'redux-action-trigger'
// ...
function doSomething (data) {
    return wrapAction({
        type: TEST_TRIGGER,
        data
    })
}

Also, redux-action-trigger size is just 1.95 Kb uncompressed.

Author

Vladimir Metnew vladimirmetnew@gmail.com

LICENSE

MIT

Package Sidebar

Install

npm i redux-action-trigger

Weekly Downloads

0

Version

0.2.3

License

MIT

Last publish

Collaborators

  • metnew