client/src/store/configureStore.js
author ymh <ymh.work@gmail.com>
Tue, 20 Jun 2017 14:13:15 +0200
changeset 62 b2514a9bcd49
parent 59 1eb52770eefa
child 67 9206af01f5e5
permissions -rw-r--r--
migrate to redux-offline + various optimisation

import rootReducer from '../reducers';
import rootSaga from '../sagas';
import { compose, createStore, applyMiddleware } from 'redux';
import { routerMiddleware } from 'react-router-redux';
import createSagaMiddleware from 'redux-saga'
import Immutable from 'immutable';
import { offline } from 'redux-offline';
import offlineDefaultConfig from 'redux-offline/lib/defaults';
import localForage from 'localforage';
import immutableTransform from 'redux-persist-transform-immutable'
import NoteRecord from './noteRecord'
import SessionRecord from './sessionRecord'
import APIClient from '../api/APIClient';
import createEffect from '../api';
import config from '../config';

// const composeEnhancers = (process.env.NODE_ENV !== 'production' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__) ?
//     window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({
//         shouldHotReload: false,
//     }) : compose;
const composeEnhancers = compose;


const defaultState = {
  sessions: Immutable.List([]),
  notes: Immutable.List([]),
  isAuthenticated: false,
  currentUser: null,
  token: '',
  login: Immutable.Map({
    loading: false,
    success: false,
    error: false,
  })
};

const immutableTransformConfig = {
  records: [NoteRecord, SessionRecord],
  whitelist: ['sessions', 'notes', 'currentUser']
}

const persistOptions = {
  storage: localForage,
  transforms: [immutableTransform(immutableTransformConfig)],
  whitelist: ['sessions', 'notes', 'isAuthenticated', 'currentUser', 'token']
}

const apiClient = new APIClient(config.apiRootUrl);

const offlineConfig = {
  ...offlineDefaultConfig,
  persistOptions,
  effect: createEffect(apiClient)
//  detectNetwork: callback => callback(true),
}

const storeInitialState = { ...defaultState };


export default (history, initialState = storeInitialState) => {

  const router = routerMiddleware(history);
  const saga = createSagaMiddleware();

  const store = offline(offlineConfig)(createStore)(rootReducer, initialState, composeEnhancers(
    applyMiddleware(router, saga)
  ));

  apiClient.setStore(store);

  const context = {
    client: apiClient,
    history
  }

  saga.run(rootSaga, context);

  return store;
};