|
| 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