Search code examples
reduxreact-reduxrtk-queryredux-reducers

Can't change initialState in Redux slice


I created my themeSlice with hardCoded themes in mind initialState:{theme: "lightTheme"}. I quickly realized a better way to do it was by using a simple boolean value initialState: { darkTheme: false }.

After making the changes and running the program again, I still see in console "theme": "lightTheme"

I am using React-toolkit and RTK-Query in this project, not sure if my setup is the cause.

This is my Store setup:

const rootReducer = combineReducers({
  test: testSlice,
  theme: darkThemeSlice,
  [apiSlice.reducerPath]: apiSlice.reducer,
});

const persistConfig = {
  key: "root",
  storage: AsyncStorage,
};

const persistedReducer = persistReducer(persistConfig, rootReducer);

const store = configureStore({
  reducer: persistedReducer,
  devTools: true,
  middleware: (getDefaultMiddleWare) =>
    getDefaultMiddleWare({ serializableCheck: false }).concat(
      apiSlice.middleware
    ),
});

export default store;

I cleared cache and re-ran my app, and nothing changed.

Any idea what is happening here?


Solution

  • You are using redux-persist. initialState is "the state if there is no state already - but in your case there is always the state from when you were on that website before.
    As such, initialState in your case only takes place when a user visits the website for the first time, ever.

    If you are still in development, you can just use your browser devtools to reset local storage. If this is deployed somewhere, you cannot go into all your users' browsers, so you will have to create a migration in redux-persist to move people from your first initial state to your second initial state. (Especially necessary if your state changes structure!)