Skip to content

Instantly share code, notes, and snippets.

@hoschi
Created May 11, 2016 16:56
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save hoschi/6538249ad079116840825e20c48f1690 to your computer and use it in GitHub Desktop.
Save hoschi/6538249ad079116840825e20c48f1690 to your computer and use it in GitHub Desktop.
Hot reloadable redux-saga ... sagas
import { applyMiddleware, createStore } from 'redux';
import createSagaMiddleware from 'redux-saga';
import rootReducer from './rootReducer';
import SagaManager from './SagaManager';
export default function configureStore (initialState = {}) {
// create saga middleware
const sagaMiddleware = createSagaMiddleware();
// create middleware function, which contains all normal
let middleware = applyMiddleware(sagaMiddleware);
// Create final store and subscribe router in debug env ie. for devtools
const store = middleware(createStore)(rootReducer, initialState);
// run sagas
SagaManager.startSagas(sagaMiddleware);
// enable hot module reloading for reducers
if (module.hot) {
module.hot.accept('./rootReducer', () => {
store.replaceReducer(require('./rootReducer').default);
});
module.hot.accept('./SagaManager', () => {
SagaManager.cancelSagas(store);
require('./SagaManager').default.startSagas(sagaMiddleware);
});
}
return store;
}
import mySaga from 'mySaga';
import { take, fork, cancel } from 'redux-saga/effects';
const sagas = [mySaga];
export const CANCEL_SAGAS_HMR = 'CANCEL_SAGAS_HMR';
function createAbortableSaga (saga) {
if (process.env.NODE_ENV === 'development') {
return function* main () {
const sagaTask = yield fork(saga);
yield take(CANCEL_SAGAS_HMR);
yield cancel(sagaTask);
};
} else {
return saga;
}
}
const SagaManager = {
startSagas(sagaMiddleware) {
sagas.map(createAbortableSaga).forEach((saga) => sagaMiddleware.run(saga));
},
cancelSagas(store) {
store.dispatch({
type: CANCEL_SAGAS_HMR
});
}
};
export default SagaManager;
@hoschi
Copy link
Author

hoschi commented May 12, 2016

See this issue for more context and potential problems.

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