How to stop redux-form's “form” state from auto-rehydrated by redux-persit

烂漫一生 提交于 2019-12-04 07:28:14

I have a "perfect" solution based on suggestion by @jpdelatorre from this thread How to handle redux-form/CHANGE in reducer

Basically it's to "extend" the formReducer provided by redux-form, then add switch case for the event "REHYDRATE":

import { reducer as reduxFormReducer } from 'redux-form'
import { REHYDRATE } from 'redux-persist/constants'

const formPlugin = {
    my_redux_form_name: (state, action) => {
        switch (action.type) {
            case REHYDRATE:
                return {}

            default:
                return state
        }
    }
}

const formReducer = reduxFormReducer.plugin(formPlugin)
export default formReducer

then have the extended reducer to register with the root reducer.

import formReducer from './form.reducer'
const rootReducer = combineReducers({
    ...other reducers,
    form: formReducer
})

If you are using the latest (v5) redux-persist version, in the persistConfig option there's a whitelist key-option where you whitelist which reducers should be persisted/rehydrated. You should use that, e.g:

const persistConfig = { key: 'root_key_in_localstorage', storage, whitelist: ['session'], }

You can use a Middleware that will handle this specific action type and prevent it from being passed to the reducers.

const myMiddleWare = store => next => action => {
  if(action.type != 'REHYDRATE'){
     next(action); // pass the action forward to the reducers
  } else{
    // do your logic here, you can use store.dispatch to dispatch other actions
    // when your not invoking  next(action) this action won't pass through to all the reducers
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!