Inject Reducers and Sagas asynchronously for React Native

Viewed 702

I have a web application made from reactjs, redux and react-router where i used the code splitting technique to inject sagas and reducers asynchronously. Now that i want to use react native. I have come to know react navigation is the best bet in the game of routing. However i have no idea how can i inject sagas and reducers asynchronously like i have done with react router.

routes.js

import { getAsyncInjectors } from './utils/asyncInjectors';
import AppReducer from './containers/App/reducers';
import AppSagas from './containers/App/sagas';

const errorLoading = (err) => {
  console.error('Dynamic page loading failed', err); // eslint-disable-line no-console
};

const loadModule = (cb) => (componentModule) => {
  cb(null, componentModule.default);
};

export default function createRoutes(store) {
  // Create reusable async injectors using getAsyncInjectors factory
  const { injectReducer, injectSagas } = getAsyncInjectors(store); // eslint-disable-line no-unused-vars

  // We need these reducers and saga upfront
  injectReducer('global', AppReducer);
  injectSagas(AppSagas);

  return [
    {
      path: '/',
      name: 'Dashboard',
      getComponent(nextState, cb) {
        const importModules = Promise.all([
          System.import('./containers/HomeScreen'),
        ]);

        const renderRoute = loadModule(cb);

        importModules.then(([component]) => {
          renderRoute(component);
        });

        importModules.catch(errorLoading);
      },
    },
  ];
}


export function injectAsyncReducer(store, isValid) {
  return function injectReducer(name, asyncReducer) {
    if (!isValid) checkStore(store);

    invariant(
      isString(name) && !isEmpty(name) && isFunction(asyncReducer),
      '(app/utils...) injectAsyncReducer: Expected `asyncReducer` to be a reducer function'
    );

    if (Reflect.has(store.asyncReducers, name)) return;

    store.asyncReducers[name] = asyncReducer; // eslint-disable-line no-param-reassign
    store.replaceReducer(createReducer(store.asyncReducers));
  };
}

export function getAsyncInjectors(store) {
  checkStore(store);

  return {
    injectReducer: injectAsyncReducer(store, true),
    injectSagas: injectAsyncSagas(store, true),
  };
}

How can i apply the same concept when using react navigation? And would this bring any benefit to the application initial load time?

0 Answers
Related