rt2zz / redux-persist

persist and rehydrate a redux store
MIT License
12.97k stars 867 forks source link

Handle storage depending a condition #1137

Closed paulomfr closed 1 year ago

paulomfr commented 4 years ago

Hi, great job with redux-persist!

I am trying to do a "Keep Logged" condition, trying to change of sessionStorage to localStorage depending if checkbox is marked. Can you help me?

// authReducer.js
import { createActions, createReducer } from 'reduxsauce';
import session from 'redux-persist/lib/storage/session';
import { persistReducer } from 'redux-persist';
import autoMergeLevel2 from 'redux-persist/lib/stateReconciler/autoMergeLevel2';

export const { Types, Creators } = createActions({
  doLoginStart: [''],
  doLoginSuccess: ['data', 'keepLogged'],
  doLoginError: ['error'],
  doLogout: ['']
});

const persist = {
  key: 'auth',
  storage: session,
  blacklist: ['isLogging', 'error'],
  stateReconciler: autoMergeLevel2
};

const INITIAL_STATE = {
  data: {},
  error: {},
  keepLogged: false,
  isLoggedIn: false,
  isLogging: false
};

const loginStart = (state = INITIAL_STATE) => ({
  ...state,
  isLogging: true
});

const loginError = (state = INITIAL_STATE, { error }) => ({
  ...state,
  error,
  isLogging: false
});

const loginSuccess = (state = INITIAL_STATE, { data, keepLogged }) => ({
  ...state,
  data,
  keepLogged,
  isLoggedIn: true,
  isLogging: false
});

const logout = () => ({
  ...INITIAL_STATE
});

const HANDLERS = {
  [Types.DO_LOGIN_START]: loginStart,
  [Types.DO_LOGIN_ERROR]: loginError,
  [Types.DO_LOGIN_SUCCESS]: loginSuccess,
  [Types.DO_LOGOUT]: logout
};

const reducer = createReducer(INITIAL_STATE, HANDLERS);

export default persistReducer(persist, reducer);
// store.js
import { createStore, compose, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';

import reducers from './ducks';

const middlewares = [thunk];

const persist = {
  key: 'root',
  storage,
  whitelist: []
};

/* eslint-disable no-underscore-dangle */
const composeEnhancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
/* eslint-enable */

const initialState = {};
const persisted = persistReducer(persist, reducers);

const store = createStore(
  persisted,
  initialState,
  composeEnhancer(applyMiddleware(...middlewares))
);

const persistor = persistStore(store);

export { store, persistor };
potatosalad94 commented 3 months ago

Hello @paulomfr I have the same problem, did you find a solution for this ?