Redux-persist
lastmod 2024-02-25created 2023-02-134 edits
Install
How to apply with redux-toolkit
Create a createPersistor utility function in the src/stores/persist.ts file:
import {ReducersMapObject, configureStore, combineReducers} from '@reduxjs/toolkit';
import {
persistStore,
persistReducer,
FLUSH,
REHYDRATE,
PAUSE,
PERSIST,
PURGE,
REGISTER,
DEFAULT_VERSION,
} from 'redux-persist';
import storage from 'redux-persist/lib/storage';
export const DEFAULT_IGNORED_ACTIONS = [
FLUSH,
REHYDRATE,
PAUSE,
PERSIST,
PURGE,
REGISTER,
];
export function createPersistor(
key: string,
reducers: ReducersMapObject<{}, any>,
version = DEFAULT_VERSION,
ignoredActions = DEFAULT_IGNORED_ACTIONS
) {
const persistConfig = {key, version, storage};
const rootReducer = combineReducers(reducers);
const persistedReducer = persistReducer(persistConfig, rootReducer);
const store = configureStore({
reducer: persistedReducer,
middleware: getDefaultMiddleware =>
getDefaultMiddleware({
serializableCheck: {
ignoredActions,
},
}),
});
const persistor = persistStore(store);
return {store, persistor};
}
Add the function created above and the reducers to register in the src/stores/store.ts file.
import {createPersistor} from './persist';
import {workReducer} from './apis/work'; // 사용자가 직접 만든 리듀서 API
export const DEFAULT_PERSIST_KEY = 'steel:inspection';
export const {store, persistor} = createPersistor(DEFAULT_PERSIST_KEY, {
work: workReducer,
});
Then apply it to App.js as described in #PersistGate.
PersistGate
In src/App.js, apply persistence by using #PersistGate inside Redux#Provider.
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import './plugins/chart/register';
import {router} from './routes/router';
import {store, persistor} from './stores/store';
import {RouterProvider} from 'react-router-dom';
import {Provider} from 'react-redux';
import {PersistGate} from 'redux-persist/integration/react';
const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement);
root.render(
<React.StrictMode>
<Provider store={store}>
<PersistGate loading={null} persistor={persistor}>
<RouterProvider router={router} />
</PersistGate>
</Provider>
</React.StrictMode>
);