Skip to content

Commit c946aaa

Browse files
committed
feat(middleware): redux-persist support
Signed-off-by: Sudhanshu Dasgupta <[email protected]>
1 parent 356d095 commit c946aaa

File tree

4 files changed

+265
-2
lines changed

4 files changed

+265
-2
lines changed

package-lock.json

Lines changed: 80 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@
4646
"@reduxjs/toolkit": "^2.2.5",
4747
"@testing-library/react": "^14.1.2",
4848
"@types/jest": "^29.5.11",
49+
"@types/lodash": "^4.17.7",
4950
"@types/react": "^18.2.45",
5051
"@types/react-dom": "^18.2.18",
5152
"@typescript-eslint/eslint-plugin": "^6.12.0",
@@ -61,12 +62,14 @@
6162
"jest": "^29.7.0",
6263
"jest-environment-jsdom": "^29.7.0",
6364
"lint-staged": "^14.0.1",
65+
"lodash": "^4.17.21",
6466
"mui-datatables": "^4.3.0",
6567
"notistack": "^3.0.1",
6668
"prettier": "^3.0.3",
6769
"prettier-plugin-organize-imports": "^3.2.3",
6870
"react-error-boundary": "^4.0.12",
6971
"react-markdown": "^8.0.7",
72+
"react-redux": "^8.1.3",
7073
"rehype-raw": "^6.1.1",
7174
"remark-gfm": "^3.0.1",
7275
"ts-jest": "^29.1.1",

src/index.tsx

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,5 +3,6 @@ export * from './base';
33
export * from './colors';
44
export * from './custom';
55
export * from './icons';
6+
export * from './redux-persist';
67
export * from './schemas';
78
export * from './theme';

src/redux-persist/index.tsx

Lines changed: 181 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,181 @@
1+
/* eslint-disable @typescript-eslint/no-explicit-any */
2+
3+
import _ from 'lodash';
4+
import { FC, ReactNode, useEffect, useState } from 'react';
5+
import { useDispatch } from 'react-redux';
6+
import { Dispatch } from 'redux';
7+
8+
const INVALID_REDUCER_PATH = Symbol('INVALID_REDUCER_PATH');
9+
const REHYDRATE_STATE_ACTION = 'REHYDRATE_STATE_ACTION';
10+
11+
// Define types for the actions
12+
interface RehydrateStateAction {
13+
type: typeof REHYDRATE_STATE_ACTION;
14+
payload: {
15+
reducerPath: string;
16+
inflatedState: unknown;
17+
};
18+
}
19+
20+
type Action = RehydrateStateAction | { type: string; [key: string]: unknown };
21+
22+
// Define the shape of the actionsToPersist object
23+
interface ActionsToPersist {
24+
[actionType: string]: string[];
25+
}
26+
27+
/**
28+
* Creates an action to rehydrate state.
29+
*
30+
* @param {string} reducerPath - The path of the reducer to rehydrate.
31+
* @param {unknown} inflatedState - The state to rehydrate with.
32+
* @returns {RehydrateStateAction} An action object for rehydrating state.
33+
*/
34+
const rehydrateState = (reducerPath: string, inflatedState: unknown): RehydrateStateAction => {
35+
return {
36+
type: REHYDRATE_STATE_ACTION,
37+
payload: {
38+
reducerPath,
39+
inflatedState
40+
}
41+
};
42+
};
43+
44+
/**
45+
* Reducer to handle state rehydration during Redux store updates.
46+
* This reducer intercepts a specific action type to rehydrate the state of specified reducers.
47+
*
48+
* @param {unknown} state - The current state.
49+
* @param {Action} action - The dispatched action.
50+
* @returns {unknown} The new state after rehydration.
51+
*/
52+
const rehydrateStateReducer = (state: unknown, action: Action): unknown => {
53+
if (action.type === REHYDRATE_STATE_ACTION) {
54+
const appState = _.cloneDeep(state);
55+
_.set(
56+
appState as object,
57+
(action.payload as RehydrateStateAction['payload']).reducerPath.split('/'),
58+
(action.payload as RehydrateStateAction['payload']).inflatedState
59+
);
60+
return appState;
61+
}
62+
return state;
63+
};
64+
65+
/**
66+
* Initializes Redux persistence with given actions to persist on
67+
*
68+
* @param {ActionsToPersist} actionsToPersist - An object mapping action types to arrays of reducer paths.
69+
* Each action type is associated with an array of reducer paths whose state should be persisted.
70+
* @returns {Object} An object containing Redux persistence functions.
71+
*/
72+
export const initReduxPersist = (actionsToPersist: ActionsToPersist) => {
73+
/**
74+
* Creates a new reducer with enhanced state rehydration logic for Redux persistence.
75+
* This function returns a new reducer that first rehydrates the state using the
76+
* rehydrateStateReducer, and then applies the original reducer to the rehydrated state.
77+
*
78+
* @param {function} reducer - The original reducer function to enhance.
79+
* @returns {function} A new enhanced reducer function with added state rehydration.
80+
*/
81+
const createPersistEnhancedReducer =
82+
(reducer: (state: unknown, action: Action) => unknown) =>
83+
(state: unknown, action: Action): unknown => {
84+
const newState = rehydrateStateReducer(state, action);
85+
return reducer(newState, action);
86+
};
87+
88+
/**
89+
* Redux middleware to persist state to local storage based on dispatched actions.
90+
* This middleware listens for specific actions and saves the relevant state to local storage.
91+
*
92+
* @param {any} store - The Redux store.
93+
* @returns {Function} A middleware function.
94+
*/
95+
const persistMiddleware =
96+
(store: any) =>
97+
(next: (action: Action) => unknown) =>
98+
(action: Action): unknown => {
99+
const result = next(action);
100+
101+
const reducersToPersist = actionsToPersist[action.type];
102+
103+
if (reducersToPersist) {
104+
const appState = store.getState();
105+
reducersToPersist.forEach((reducerPath) => {
106+
const path = reducerPath.split('/');
107+
const stateToPersist = _.get(appState, path, INVALID_REDUCER_PATH);
108+
109+
if (stateToPersist === INVALID_REDUCER_PATH) {
110+
throw new Error(`Reducer Path to Persist Is Invalid: ${reducerPath}`);
111+
}
112+
113+
localStorage.setItem(reducerPath, JSON.stringify(stateToPersist));
114+
});
115+
}
116+
return result;
117+
};
118+
119+
/**
120+
* Action creator to load persisted state from local storage during Redux store initialization.
121+
* This function retrieves previously saved state from local storage and dispatches rehydration actions.
122+
*
123+
* @returns {Function} A thunk function.
124+
*/
125+
const loadPersistedState = () => (dispatch: Dispatch) => {
126+
Object.values(actionsToPersist).forEach((reducerPaths) => {
127+
reducerPaths.forEach((path) => {
128+
let inflatedState = localStorage.getItem(path);
129+
try {
130+
if (inflatedState) {
131+
inflatedState = JSON.parse(inflatedState);
132+
dispatch(rehydrateState(path, inflatedState));
133+
}
134+
} catch (e) {
135+
console.error(`Error rehydrating state for reducer ${path}`, inflatedState);
136+
}
137+
});
138+
});
139+
};
140+
141+
return {
142+
persistMiddleware,
143+
createPersistEnhancedReducer,
144+
loadPersistedState
145+
};
146+
};
147+
148+
// Define types for PersistedStateProvider props
149+
interface PersistedStateProviderProps {
150+
children: ReactNode;
151+
loadPersistedState: () => (dispatch: Dispatch) => void;
152+
}
153+
154+
export const PersistedStateProvider: FC<PersistedStateProviderProps> = ({
155+
children,
156+
loadPersistedState
157+
}) => {
158+
const [loading, setLoading] = useState(true);
159+
const [error, setError] = useState<Error | null>(null);
160+
const dispatch = useDispatch();
161+
162+
useEffect(() => {
163+
if (!loading) {
164+
return;
165+
}
166+
try {
167+
dispatch(loadPersistedState() as any);
168+
} catch (e) {
169+
setError(e as Error);
170+
}
171+
setLoading(false);
172+
}, [loading, dispatch, loadPersistedState]);
173+
174+
error && console.error('Error Loading Persisted State', error);
175+
176+
if (loading) {
177+
return null;
178+
}
179+
180+
return <>{children}</>;
181+
};

0 commit comments

Comments
 (0)