Search code examples
javascriptreduxredux-persist

it is necessary to implement the case REHYDRATE in redux-persist?


I am working on a proof of concept in react-native and I am using redux-persist. According to what I read the states are automatically assigned in version 5, however I have not managed to rehydrate the state without the case REHYDRATE.

My reducer:

import {ADD_USER} from '../constants/actionTypes';
import { REHYDRATE } from 'redux-persist';


const initialState = {
    userName: null,
    fetching: false
};

const userReducer = (state = initialState, action) => {
    let copied = Object.assign({}, state);
    switch (action.type){
        case ADD_USER:
            copied.userName = action.payload;
            break;
        case REHYDRATE:
            //console.log('Payload desde el reducer ', action.payload);fsdffdsdsfsdfsdf
            copied = action.payload.userReducer;
            break;
        default:
            break;
    }

    return copied;
};

export default userReducer;

My configureStore

const persistConfig = {
    key: 'root',
    storage,
    stateReconciler: autoMergeLevel2,
};

function logger({ getState }) {
    return (next) => (action) => {
        let returnValue = next(action)
        return returnValue
    }
}

const persistedReducer = persistCombineReducers(persistConfig, {userReducer});

export default () => {
    let store = createStore(persistedReducer, undefined, applyMiddleware(logger));
    let persistor = persistStore(store, null, () => {
        Alert.alert(
            'Current state',
            JSON.stringify(store.getState()),
            [
                {text: 'OK', onPress: () => console.log('OK Pressed')},
            ],
            { cancelable: false }
        );
    });
    return { store, persistor }
}

Solution

  • My problem was that I returned the state at the end of the method instead of returning it in each case of the switch and this surely broke the auto rehydration. Changing the reducer returns my problem disappeared.

    The reducer code was like this:

    const initialState = {
        userName: null,
        fetching: false
    };
    
    const userReducer = (state = initialState, action) => {
        switch (action.type){
            case ADD_USER:{
                let copied = Object.assign({}, state);
                copied.userName = action.payload;
                return copied;
            }
            default:
                return state;
        }
    };
    
    export default userReducer;