@redux-devtools/core
Version:
Redux DevTools with hot reloading and time travel
57 lines • 1.9 kB
JavaScript
export default function persistState(sessionId) {
let deserializeState = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : state => state;
let deserializeAction = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : state => state;
if (!sessionId) {
return next => function () {
return next(...arguments);
};
}
function deserialize(state) {
return {
...state,
actionsById: Object.fromEntries(Object.entries(state.actionsById).map(_ref => {
let [actionId, liftedAction] = _ref;
return [actionId, {
...liftedAction,
action: deserializeAction(liftedAction.action)
}];
})),
committedState: deserializeState(state.committedState),
computedStates: state.computedStates.map(computedState => ({
...computedState,
state: deserializeState(computedState.state)
}))
};
}
return next => (reducer, initialState) => {
const key = `redux-dev-session-${sessionId}`;
let finalInitialState;
try {
const json = localStorage.getItem(key);
if (json) {
finalInitialState = deserialize(JSON.parse(json)) || initialState;
next(reducer, initialState);
}
} catch (e) {
console.warn('Could not read debug session from localStorage:', e); // eslint-disable-line no-console
try {
localStorage.removeItem(key);
} finally {
finalInitialState = undefined;
}
}
const store = next(reducer, finalInitialState);
return {
...store,
dispatch(action) {
store.dispatch(action);
try {
localStorage.setItem(key, JSON.stringify(store.getState()));
} catch (e) {
console.warn('Could not write debug session to localStorage:', e); // eslint-disable-line no-console
}
return action;
}
};
};
}