Redux: replaceReducer don't replace

Created on 6 Jan 2018  路  1Comment  路  Source: reduxjs/redux

import { createStore } from 'redux';
import rootReducer from '../reducers';

export default (initialState = {}) =>  {
  const store = createStore(rootReducer, initialState);

  if (module.hot) {
    module.hot.accept('../reducers', () => {
      import('../reducers').then(module => {
        console.log(createStore(module.default).getState());

        store.replaceReducer(module.default);

        console.log(store.getState());
      });
    });
  }

  return store;
};

First console.log new store which should succeed, second console.log store after replaceReducer, but store didn't replace, What I do is not correct?

screen shot 2018-01-06 at 3 56 42 pm

Most helpful comment

replaceReducer only replaces the reducer function the store uses to compute the new state when an action is dispatched. However, it leaves the current state of the store unchanged. The new reducer function will be used when the next action is dispatched, but since the initialState has already been set, any initialState in the new reducer will not be used.

If you want to reset the initialState in addition to replacing the reducer, you could try making a RESET action that is handled by the reducer appropriately. i.e.

import('../reducers').then(module => {
  store.replaceReducer(module.default);
  store.dispatch({ type: 'RESET' });
  console.log(store.getState());
});

>All comments

replaceReducer only replaces the reducer function the store uses to compute the new state when an action is dispatched. However, it leaves the current state of the store unchanged. The new reducer function will be used when the next action is dispatched, but since the initialState has already been set, any initialState in the new reducer will not be used.

If you want to reset the initialState in addition to replacing the reducer, you could try making a RESET action that is handled by the reducer appropriately. i.e.

import('../reducers').then(module => {
  store.replaceReducer(module.default);
  store.dispatch({ type: 'RESET' });
  console.log(store.getState());
});
Was this page helpful?
0 / 5 - 0 ratings