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

redux-persist

https://juejin.im/entry/57cac7b167f3560057bb00a7

Design principle

  1. Similarity in cross-platform
    1. Whitelist
    2. Saga must be bundled to store as middleware
    3. So as autoRehydrate that is also a middleware to merge subsequent delta of in-memory store to persistent storage
    4. However, it is usually pointless to execute Saga prior to completion of Rehydate
    5. Thus, rootSaga should be executed on callback of persistStore
  2. Yet, HOF is required since
    1. Reducer may be platform-specific
    2. Saga may be platform-specific
    3. InitialState is usually programmed for unit test, in other word, changes prior to build
    4. Storage is inevitably platform-specific
    5. Additional middleware may be available
    6. 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;

results matching ""

    No results matching ""