Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'redux-persist' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
import { createStore } from 'redux';
import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';
import autoMergeLevel1 from 'redux-persist/lib/stateReconciler/autoMergeLevel1';
import reducers from './reducers';
const persistConfig = {
key: 'root',
storage,
stateReconciler: autoMergeLevel1
}
const persistedReducer = persistReducer(persistConfig, reducers)
export const store = createStore(persistedReducer);
// export const persistor = persistStore(store, null, () => {console.log('Rehydrated')});
export const persistor = persistStore(store);
// #region configure logger middleware
const loggerMiddleware = createLogger({
level: 'info',
collapsed: true
});
// #endregion
// #region createStore : enhancer
const enhancer = composeWithDevTools(
applyMiddleware(
thunkMiddleware,
fetchMiddleware,
loggerMiddleware,
),
autoRehydrate()
);
// #endregion
// #region store initialization
export default function configureStore(initialState) {
const store = createStore(reducer, initialState, enhancer);
// begin periodically persisting the store
persistStore(store);
// OPTIONAL: you can blacklist reducers to avoid them to persist, so call
// persistStore(
// store,
// {blacklist: ['someTransientReducer']},
// () => {
// console.log('rehydration complete')
/* ------------- Saga Middleware ------------- */
const sagaMonitor = __DEV__ ? console.tron.createSagaMonitor() : null
const sagaMiddleware = createSagaMiddleware({ sagaMonitor })
middleware.push(sagaMiddleware)
/* ------------- Assemble Middleware ------------- */
enhancers.push(applyMiddleware(...middleware))
/* ------------- AutoRehydrate Enhancer ------------- */
// add the autoRehydrate enhancer
if (ReduxPersist.active) {
enhancers.push(autoRehydrate())
}
// if Reactotron is enabled (default for __DEV__), we'll create the store through Reactotron
const createAppropriateStore = Config.useReactotron ? console.tron.createStore : createStore
const store = createAppropriateStore(rootReducer, compose(...enhancers))
// configure persistStore and check reducer version number
if (ReduxPersist.active) {
RehydrationServices.updateReducers(store)
}
// kick off root saga
sagaMiddleware.run(rootSaga)
return store
}
const config = {
key: 'root',
storage,
blacklist: ['loadingReducer'],
debug: true //to get useful logging
};
const middleware = [];
const sagaMiddleware = createSagaMiddleware();
middleware.push(sagaMiddleware);
if (__DEV__) {
middleware.push(createLogger());
}
const reducers = persistCombineReducers(config, rootReducers);
const enhancers = [applyMiddleware(...middleware)];
// const initialState = {};
const persistConfig = { enhancers };
let store = createStore(reducers, undefined, compose(...enhancers));
const persistor = persistStore(store, persistConfig, () => {
// console.log('Test', store.getState());
});
const configureStore = () => {
return { persistor, store };
};
sagaMiddleware.run(sagas);
export default configureStore;
export const configureStore = () => {
// redux-persist config
const persistConfig = {
version: 1,
key: 'root',
migrate: createMigrate(migrations as any, { debug: electronIsDev }),
storage,
transforms: [functionTransform, outputTransformers, passwordTransform],
blacklist: ['notifications']
};
const persistedReducer = persistReducer(persistConfig, rootReducer);
const composeEnhancers =
(window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const middlewares = [thunk as ThunkMiddleware];
if (electronIsDev) {
middlewares.push(
createLogger({
predicate: (_, action) => !/^@@/.test(action.type),
collapsed: true
const persistConfig = {
whitelist: ['entities', 'pagination']
};
// window.__data = initial state passed down by server to client
let initialState = window.__data; // eslint-disable-line
try {
const restoredState = await getStoredState(persistConfig);
initialState = merge({}, initialState, restoredState);
} catch (error) {
console.log('error restoring state:', error);
}
const dest = document.getElementById('content');
const store = configureStore(history, initialState);
const persistor = createPersistor(store, persistConfig); // eslint-disable-line
store.runSaga(rootSaga);
render(
,
dest
);
if (process.env.NODE_ENV !== 'production') {
window.React = React; // enable debugger
}
}
/* eslint-disable no-underscore-dangle */
const devtoolsExtensionCompose = isDevelopment
&& isObject(window)
&& window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__;
/* eslint-enable no-underscore-dangle */
const middleware = isDevelopment
? [thunkMiddleware, createLogger({ diff: true, collapsed: true })]
: [thunkMiddleware];
const composeEnhancers = devtoolsExtensionCompose || compose;
const enhancer = composeEnhancers(applyMiddleware(...middleware));
export const store = createStore(rootReducer, enhancer);
export const persistor = persistStore(store);
/* eslint-enable no-undef */
const enhancer = composeEnhancers(...enhancers);
const persistConfig = {
key: 'root',
storage,
};
const persistedReducer = persistReducer(persistConfig, reducer);
export const store = createStore(
persistedReducer,
{},
enhancer,
);
export const persistor = persistStore(store);
const configureStore = callback => {
// mount it on the Store
const store = createStore(
rootReducer,
initialState,
compose(
// if you use getStoredState then no need to use auto hydrate to get state back
autoRehydrate(),
applyMiddleware(...middleware),
)
)
// then run the saga
sagaMiddleware.run(rootSaga)
persistStore(store, {storage: AsyncStorage}, ()=> callback(store))
}
import { AsyncStorage } from 'react-native';
import { createStore, applyMiddleware } from 'redux';
import { persistStore, autoRehydrate, purgeStoredState } from 'redux-persist';
import appReducer from '../reducers/AppReducer';
const todosStore = createStore(
appReducer,
undefined,
autoRehydrate()
);
persistStore(todosStore, {storage: AsyncStorage});
// purgeStoredState({storage: AsyncStorage}) // Clear persistStore
export default todosStore;