1 import rootReducer from '../reducers'; |
1 import rootReducer from '../reducers'; |
|
2 import rootSaga from '../sagas'; |
|
3 import { loadSessions } from '../actions/sessionsActions'; |
2 import { createStore, applyMiddleware } from 'redux'; |
4 import { createStore, applyMiddleware } from 'redux'; |
3 import { routerMiddleware } from 'react-router-redux'; |
5 import { routerMiddleware } from 'react-router-redux'; |
|
6 import createSagaMiddleware from 'redux-saga' |
4 import Immutable from 'immutable'; |
7 import Immutable from 'immutable'; |
5 |
|
6 const loadState = () => { |
|
7 try { |
|
8 const serializedState = localStorage.getItem('state'); |
|
9 if (!serializedState) { |
|
10 return {}; |
|
11 } |
|
12 return JSON.parse(serializedState); |
|
13 } catch (err) { |
|
14 return {}; |
|
15 } |
|
16 } |
|
17 |
|
18 const saveState = (state) => { |
|
19 try { |
|
20 localStorage.setItem('state', JSON.stringify(state)); |
|
21 } catch (err) {} |
|
22 } |
|
23 |
|
24 const savedState = loadState(); |
|
25 |
8 |
26 const defaultState = { |
9 const defaultState = { |
27 currentSession: null, |
10 currentSession: null, |
28 sessions: Immutable.List(savedState.sessions || []), |
11 sessions: Immutable.List([]), |
29 notes: Immutable.List(savedState.notes || []), |
12 notes: Immutable.List([]), |
30 isAuthenticated: false, |
13 isAuthenticated: false, |
31 }; |
14 }; |
32 |
15 |
33 const storeInitialState = Immutable.Map(defaultState); |
16 const storeInitialState = Immutable.Map(defaultState); |
34 |
17 |
35 export default (history, initialState = storeInitialState) => { |
18 export default (history, initialState = storeInitialState) => { |
36 |
19 |
37 const middleware = routerMiddleware(history); |
20 const router = routerMiddleware(history); |
38 const store = createStore(rootReducer, initialState, applyMiddleware(middleware)); |
21 const saga = createSagaMiddleware(); |
39 |
22 |
40 store.subscribe(() => { |
23 const store = createStore(rootReducer, initialState, applyMiddleware(router, saga)); |
41 const state = store.getState().toJSON(); |
|
42 const stateToPersist = { |
|
43 sessions: state.sessions, |
|
44 notes: state.notes, |
|
45 }; |
|
46 |
24 |
47 saveState(stateToPersist); |
25 saga.run(rootSaga) |
48 }); |
26 |
|
27 store.dispatch(loadSessions()); |
49 |
28 |
50 return store; |
29 return store; |
51 }; |
30 }; |