Search code examples
reactjsreact-nativereduxreact-reduxredux-thunk

Redux Toolkit Migration


I want to migrate my app thay use redux, redux-thunk and redux-persist to reduxToolkit, but I don't know how to do it with my initial configuration, here my code:

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

export default function getConfiguredStore(initialState, config) {
  const rootReducer = combineReducers(reducers);
  const persistedReducer = persistReducer(persistConfig, rootReducer);
  let appReducer = rootReducer;
  if (config.usePersist) {
    appReducer = persistedReducer;
  }
  const rootAppReducer = authReducer(appReducer);

  const store = createStore(
      rootAppReducer,
      initialState,
      composeEnhancers(
          applyMiddleware(
              multiClientMiddleware(axiosConfig),
              thunkMiddleware,
              authMiddleware( ),
              createLogger( true ),
          )
      ),
  );
  const persistor = persistStore(store, null, () => {
    if (config.useLogger) {
      console.log('REHYDRATED');
    }
  });
  //persistor.purge() //TO clean state.

  return {store, persistor};
}


Solution

  • The "Modern Redux with Redux Toolkit" tutorial page in the Redux docs shows how to migrate existing Redux logic to use RTK. Summarizing:

    • Replace your existing store setup logic with a call to configureStore()
    • Pick a reducer and its associated actions. Replace with createSlice. Repeat as needed.

    In your case, the key part would be to switch the const store = createStore() part for this:

      const store = configureStore({
        reducer: rootAppReducer,
        preloadedState: initialState,
        middleware: getDefaultMiddleware => {
          return getDefaultMiddleware()
            .prepend(multiClientMiddleware(axiosConfig))
            .concat(authMiddleware, createLogger( true ));
        })
      });