Search code examples
reactjsreduxreact-reduxthunk

Error: Expected the root reducer to be a function. Instead, received: 'undefined'


I keep running into this error!

Error: Expected the root reducer to be a function. Instead, received: 'undefined'

I've tried every answer I could find to no avail, here is all the pertinent stuff!

Root Reducer

const createRootReducer = (history) => {
      combineReducers({
        router: connectRouter(history),
        createUser: signupReducer,
      });
    };

    export default createRootReducer;

Root

const Root = ({ children, initialState = {} }) => {
  const history = createBrowserHistory();
  const middleware = [thunk, routerMiddleware(history)];

  const store = createStore(rootReducer(history), initialState, applyMiddleware(...middleware));

  return (
    <Provider store={store}>
      <ConnectedRouter history={history}>{ children }</ConnectedRouter>
    </Provider>
  );
};

export default Root;

App

function App() {
  return (
    <div className="App">
      <Root>
        <ToastContainer hideProgressBar={true} newestOnTop={true} />
        <Navbar />
        <Landing />
        <PostList />
      </Root>
    </div>
  );
}

export default App;

and the Signup reducer

export const signupReducer = (state = initialState, action) => {
  switch (action.type) {
    case UserTypes.CREATE_USER_SUBMITTED:
      return {
        usernameError: "",
        passwordError: "",
        isSubmitted: true
      };
    case UserTypes.CREATE_USER_SUCCESS:
      return {
        usernameError: "",
        passwordError: "",
        isSubmitted: false
      };
    case UserTypes.CREATE_USER_ERROR:
        const err = {
        usernameError: "",
        passwordError: "",
        isSubmitted: false
      };
      if(action.errorData.hasOwnProperty('username')){
        err.usernameError = action.errorData['username'];
      }
      if(action.errorData.hasOwnProperty('password')){
        err.passwordError = action.errorData['password'];
      }
      return err;
    default:
      return state
  }
}

this is the line throwing the error in the root component

  const store = createStore(rootReducer(history), initialState, applyMiddleware(...middleware));

Thank you for your time!


Solution

  • You need to return the combined reducer.

    const createRootReducer = (history) => {
      return combineReducers({
        router: connectRouter(history),
        createUser: signupReducer,
      });
    };
    

    Or implicitly return using an arrow function.

    const createRootReducer = (history) => combineReducers({
      router: connectRouter(history),
      createUser: signupReducer,
    });