2.0.0 • Published 7 years ago

redux-di v2.0.0

Weekly downloads
5
License
MIT
Repository
github
Last release
7 years ago

redux-di travis npm

Redux thunk middleware with dependency injection.

Simple dependency injection in the action creator. The dependency injection enables easily testable asynchronous action creators.

NB: This is an alternative to redux-thunk, which already has some of this functionality with the withExtraArgument option for an extra static argument. redux-di has a dynamic argument created with dispatch and getState as parameters which is sometimes convenient.

Install

$ npm install --save redux-di

Usage

In this example we have an api-client which is created with some token saved in the redux state. This is not currently possible with redux-thunk and is the only significant difference in redux-di.

configure store

import { createStore, applyMiddleware, compose } from 'redux';
import reduxDI from 'redux-di';

const storeDependent = {
  api: ({getState}) => initApiClient(getState().apiToken),
}
const sideEffects = {
  redirect: (href) => { location.href = href; },
}

const thunkMiddleware = reduxDI().withStatic(sideEffects).withDynamic(storeDependent);

// configure store
const initialState = {};
const rootReducer = (state: {}) => state;
const enhancer = compose(applyMiddleware(thunkMiddleware));
const store = createStore(rootReducer, initialState, enhancer);

thunks

// because api and redirect are parameters, they are easily stubbed for testing
const getUserProfile = (id) => async (dispatch, getState, { api, redirect }) => {
  try {
    dispatch({ type: 'PROFILE_BEGIN', id });
    const profile = await api.getProfile(id);
    dispatch({ type: 'PROFILE_SUCCESS', profile});
  } catch(err) {
    dispatch({ type: 'PROFILE_ERROR'}, id, err);
    redirect('http://localhost/500.html');
  }
}

dispatch thunks

dispatch(getUserProfile())

Upgrade from v1

Most likely, you do not need to upgrade, but if you do the thunk api has changed.

// v1 actionCreator.
const getProfile = (id) => ({ dispatch, getState, extraArg }) => { /* impl */ };
// v2 actionCreator.
const getProfile = (id) => (dispatch, getState, { extraArg }) => { /* impl */ };

Also, the middleware configuration has changed. See examples above

License

MIT © Sigurd Fosseng

2.0.0

7 years ago

1.0.7

7 years ago

1.0.6

7 years ago

1.0.5

7 years ago

1.0.4

7 years ago

1.0.3

7 years ago

1.0.2

8 years ago

1.0.1

8 years ago

1.0.0

8 years ago

0.0.2

8 years ago

0.0.1

8 years ago