Gianmarco
Gianmarco

Reputation: 832

redux toolkit +connected-react-router

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)],
    });

Upvotes: 4

Views: 4180

Answers (2)

Karim Ali
Karim Ali

Reputation: 107

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.

Upvotes: 2

Erik Craddock
Erik Craddock

Reputation: 31

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

Upvotes: 3

Related Questions