4

I'm trying to set up redux with connected-react-router, but I didn't really understand how to do that, I'm using the create-react-app --template redux, but if I try to do that I get the following error: Uncaught Error: Actions must be plain objects. Use custom middleware for async actions.

   import { configureStore, combineReducers } from "@reduxjs/toolkit";
    import { connectRouter, routerMiddleware } from "connected-react-router";
    import { createBrowserHistory } from "history";
    import homePageSlice from "./reducers/homepage/homePageSlice";
    
    export const history = createBrowserHistory();
    
    
    export const store = configureStore({
      reducer: {
        router: connectRouter(history),
        homepage: homePageSlice,
      },
      middleware: [routerMiddleware(history)],
    });
4
  • maybe it compains homePageSlice, if you comment out that line, do you still get the error?
    – windmaomao
    Commented Nov 22, 2021 at 13:47
  • actually I don't get that error anymore if I comment it, but how can I include also homePageSlice, it's a slice from redux toolkit, without connected-react-router it works fine
    – Gianmarco
    Commented Nov 22, 2021 at 13:54
  • 1
    While this isn't an actual answer, we recommend against trying to keep routing state in Redux today. Commented Nov 22, 2021 at 15:56
  • @Gianmarco, that means you have some code issues inside homePageSlice, just paste your definition for it then.
    – windmaomao
    Commented Nov 23, 2021 at 0:03

2 Answers 2

3

setting middleware property will override the default middleware that configureStore injects.

2
  • 5
    This answer seems too short, if you can explain more, may add example or code gist, that will be super great. :)
    – tim
    Commented Nov 26, 2021 at 1:23
  • 1
    @tim They way OP is passing an array of middlewares to configureStore overwrites the default middlewares of redux-toolkit. Setting the middleware: property like that means you want explicit, total control over the middlewares used, and none of the defaults. This kicks out the thunk middleware, which the app seems to rely on (hence the error message). The official way to keep the default middlewares and add your own is, according to the docs: middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(routerMiddleware(history)).
    – timotgl
    Commented Jan 11, 2022 at 11:02
2

Use this:

middleware: [
        actionToPlainObject,
        routerMiddleware(history)
    ]

and create actionToPlainObject.ts

import { Middleware } from '@reduxjs/toolkit';
import IStoreState from '../IStoreState';

export const actionToPlainObject: Middleware<IStoreState, any> = (store) => (
    next
) => (action) => {
    if (!action) {
        return;
    }

    return next({ ...action });
};

If using class instances this allows to be passed to Redux.

Not the answer you're looking for? Browse other questions tagged or ask your own question.