Using {...state} instead of state in persistReducer in redux

Viewed 244

So I was using redux-persist in my react-native app to persist the state and everything is working fine.

For the reducer, I was using switch-case to check for different action-types, and for the default, I was returning the state.

initialState = {
  first: null,
  second: null,
};

export default myReducer = (state = initialState, action) => {
  switch (action.type) {
    case ...:
            ... // Handling some cases which work fine
    default:
      return state;
  }
};

This thing is working fine but if I replace state with {...state} in the default block, it doesn't persist the state.

Now how much I had understood is state = {...state} so why is this not working.

Here is the persistConfig;

import AsyncStorage from "@react-native-async-storage/async-storage";
const persistConfig = {
  key: "root",
  storage: AsyncStorage,
};
1 Answers

I'm not sure this is acceptable as an answer but maybe it will shed enough light to be useful. I did a bit of digging and this is what I Found.

  1. Its not just {..state} that changes the variable, any cloning does, for example Object.assign({}, state) also breaks the persisted state.
  2. Redux persist calls the reducer quite a few times on close and on open, most of these calls state is undefined and therefore defaults to initial state (you can see this by adding console.log(state) console.log(action) in the defaults
  3. My guess is that redux persist looks out for any changes between reassignment between the given state to the reducer and the output state of the reducer and if there is a reassignment it persists that value. If this is correct then when the state gets set to initial state on close of app it wont be logged by the persistor because there is no reassignment (if you return state) but it will get logged when you clone the state in your default {...state}
Related