Skip to content

Instantly share code, notes, and snippets.

@neurosnap
Created February 6, 2017 15:18
Show Gist options
  • Save neurosnap/c52b04a52999cfad1b6b6bd13590d6d6 to your computer and use it in GitHub Desktop.
Save neurosnap/c52b04a52999cfad1b6b6bd13590d6d6 to your computer and use it in GitHub Desktop.
example plugin middleware
/* REDUCER MIDDLEWARE */
export const PluginMiddleware = (actionTypes) => store => next => action => {
action.actionTypes = actionTypes;
return next(action);
}
// example reducer
const counter = (state, action) => {
const actionTypes = action.actionTypes;
switch (action.type) {
case actionTypes.INCREMENT:
return state + 1;
case actionTypes.DECREMENT:
return state - 1;
default:
return state;
}
}
// this would be created by the plugin registry and then loaded into our init
const actionTypes = {
INCREMENT: 'INCREMENT',
SUCCESS: 'SUCCESS',
};
// exmaple store
const store = createStore({ counter }, {}, applyMiddleware(PluginMiddleware(actionTypes)));
/* SAGA MIDDLEWARE */
import createSagaMiddleware from 'redux-saga';
import { createStore, applyMiddleware } from 'redux';
// example saga
function* CounterSaga({ actionCreators, actionTypes }) {
while (true) {
const action = yield take(actionTypes.INCREMENT);
yield call(fetch, { url: '/value', method: 'POST' });
yield put(actionCreators.success());
}
}
// this would be created by the plugin registry and then loaded into our init
const actionTypes = {
INCREMENT: 'INCREMENT',
SUCCESS: 'SUCCESS',
};
// this would be created by the plugin registry and then loaded into our init
const actionCreators = {
success: { type: actionTypes.SUCCESS },
};
const sagaMiddleware = createSagaMiddleware();
// create store
const store = createStore({ counter }, {}, applyMiddleware(PluginMiddleware));
// example middleware run
sagaMiddleware.run(CounterSaga, { actionTypes, actionCreators });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment