All files / src/redux store.ts

74.07% Statements 20/27
37.5% Branches 3/8
100% Functions 4/4
74.07% Lines 20/27

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86                      1x 1x   1x 4x       1x 1x         1x 1x 1x 1x           1x 1x 1x 1x 1x                           1x                 1x               1x 1x                       1x      
import { applyMiddleware, combineReducers, createStore, Store } from "redux";
import reduxThunk from "redux-thunk";
import { composeWithDevTools } from "redux-devtools-extension";
import loadingAndErroredReducer from "./reducer";
import authReducer from "../apps/authentication/redux/reducer"; // failed to respect module here because of a circular import issue
import { dictionariesReducer } from "../apps/dictionaries";
import { conceptsReducer } from "../apps/concepts";
import { sourcesReducer } from "../apps/sources";
import { organisationsReducer } from "../apps/organisations";
import { AppState } from "./types";
 
export const STORE_VERSION = "1";
export const CURRENT_STORE_VERSION_KEY = "currentStoreVersion";
 
const doNotPersist = ["dictionaries", "concepts", "status", "sources"].reduce(
  (previousValue, item) => ({ ...previousValue, [item]: undefined }),
  {}
);
 
const saveState = (appState: AppState) => {
  const state = {
    ...appState,
    ...doNotPersist
  };
 
  try {
    localStorage.setItem("state", JSON.stringify(state));
    localStorage.setItem(CURRENT_STORE_VERSION_KEY, STORE_VERSION);
    return undefined;
  } catch (e) {
    return undefined;
  }
};
 
export const loadState = () => {
  try {
    const state = localStorage.getItem("state");
    Eif (state === null) {
      return undefined;
    }
 
    const currentStoreVersion = localStorage.getItem(CURRENT_STORE_VERSION_KEY);
    if (currentStoreVersion !== STORE_VERSION) {
      return undefined;
    }
 
    return { ...JSON.parse(state), ...doNotPersist };
  } catch (e) {
    return undefined;
  }
};
 
const rootReducer = combineReducers({
  auth: authReducer,
  status: loadingAndErroredReducer,
  dictionaries: dictionariesReducer,
  concepts: conceptsReducer,
  sources: sourcesReducer,
  organisations: organisationsReducer
});
 
const store = createStore(
  rootReducer,
  loadState(),
  process.env.NODE_ENV === "production"
    ? applyMiddleware(reduxThunk)
    : composeWithDevTools(applyMiddleware(reduxThunk))
);
 
store.subscribe(() => {
  saveState(store.getState());
});
 
export default store;
 
// required for Cypress tests
declare global {
  interface Window {
    store: Store;
  }
}
 
Iif ("Cypress" in window) {
  window.store = store;
}