( sessionId?: string | null, deserializeState: (state: S) => S = identity, deserializeAction: (action: A) => A = identity )
| 4 | import { LiftedState } from '@redux-devtools/instrument'; |
| 5 | |
| 6 | export default function persistState< |
| 7 | S, |
| 8 | A extends Action<unknown>, |
| 9 | MonitorState |
| 10 | >( |
| 11 | sessionId?: string | null, |
| 12 | deserializeState: (state: S) => S = identity, |
| 13 | deserializeAction: (action: A) => A = identity |
| 14 | ): StoreEnhancer { |
| 15 | if (!sessionId) { |
| 16 | return (next) => |
| 17 | (...args) => |
| 18 | next(...args); |
| 19 | } |
| 20 | |
| 21 | function deserialize( |
| 22 | state: LiftedState<S, A, MonitorState> |
| 23 | ): LiftedState<S, A, MonitorState> { |
| 24 | return { |
| 25 | ...state, |
| 26 | actionsById: mapValues(state.actionsById, (liftedAction) => ({ |
| 27 | ...liftedAction, |
| 28 | action: deserializeAction(liftedAction.action), |
| 29 | })), |
| 30 | committedState: deserializeState(state.committedState), |
| 31 | computedStates: state.computedStates.map((computedState) => ({ |
| 32 | ...computedState, |
| 33 | state: deserializeState(computedState.state), |
| 34 | })), |
| 35 | }; |
| 36 | } |
| 37 | |
| 38 | return (next) => |
| 39 | <S2, A2 extends Action<unknown>>( |
| 40 | reducer: Reducer<S2, A2>, |
| 41 | initialState?: PreloadedState<S2> |
| 42 | ) => { |
| 43 | const key = `redux-dev-session-${sessionId}`; |
| 44 | |
| 45 | let finalInitialState; |
| 46 | try { |
| 47 | const json = localStorage.getItem(key); |
| 48 | if (json) { |
| 49 | finalInitialState = |
| 50 | deserialize(JSON.parse(json) as LiftedState<S, A, MonitorState>) || |
| 51 | initialState; |
| 52 | next(reducer, initialState); |
| 53 | } |
| 54 | } catch (e) { |
| 55 | console.warn('Could not read debug session from localStorage:', e); // eslint-disable-line no-console |
| 56 | try { |
| 57 | localStorage.removeItem(key); |
| 58 | } finally { |
| 59 | finalInitialState = undefined; |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | const store = next( |
no test coverage detected