Introduction
- Store is the holder of reducers
- Store manages the middleware of redux-saga
- Store manages the middleware of redux-persist
- Store ensure the rootSaga is executed upon persistStore
- Store manages the middleware of logger, redux-thunk, etc
Reference
https://juejin.im/entry/57cac7b167f3560057bb00a7
Design principle
- Similarity in cross-platform
- Whitelist
- Saga must be bundled to store as middleware
- So as autoRehydrate that is also a middleware to merge subsequent delta of in-memory store to persistent storage
- However, it is usually pointless to execute Saga prior to completion of Rehydate
- Thus, rootSaga should be executed on callback of persistStore
- Yet, HOF is required since
- Reducer may be platform-specific
- Saga may be platform-specific
- InitialState is usually programmed for unit test, in other word, changes prior to build
- Storage is inevitably platform-specific
- Additional middleware may be available
- Additional whitelist may be available
// ./common/enhancers/_configureStore.js
import createSagaMiddleware from 'redux-saga'
import { persistStore, autoRehydrate } from 'redux-persist'
const common_whitelist = ['UserProfile'];
export default function({storage, rootReducer, rootSaga, whitelist, middleware}){
const sagaMiddleware = createSagaMiddleware();
whitelist = [...common_whitelist, ...whitelist];
middleware = [sagaMiddleware, ...middleware];
const enhancer = compose(
applyMiddleware(...middleware),
autoRehydrate()
);
return function _configureStore(initialState) {
const store = createStore(rootReducer, initialState, enhancer);
persistStore(store, { whitelist, storage}, () => {
sagaMiddleware.run(rootSaga);
});
return store;
}
}
// ./app/store.js
import _configureStore from '../common/store/_configureStore';
import { asyncSessionStorage } from 'redux-persist/storages'
import rootReducer from './reducers';
import rootSaga from './sagas';
const configureStore = _configureStore({
storage: asyncSessionStorage,
rootReducer,
rootSaga})
const store = configureStore();
/*
const preloadedState = window.__PRELOADED_STATE__
delete window.__PRELOADED_STATE__
const store = configureStore(preloadedState); // WebApp only
*/
export default store;