Fix – actions must be plain objects. use custom middleware for async actions
Posted on: February 21, 2021 by Pandu Rijal Pasa
If you get actions must be plain objects. use custom middleware for async actions error, here is how to fix this issue.
This error exists because you try to return a non-plain object on a redux action. For example, if you try to return another function, especially an async function, inside this action, redux doesn’t know how to handle this natively.
// redux action that returns async function
export const myAction = (payload) => async (dispatch) => {
// your action
}
To fix that, you will need custom middleware injected on your redux. You can use redux-thunk
or redux-saga
. We will use redux-thunk
in this article, so first, install the library:
// installing redux-thunk dependency
npm install --save redux-thunk
Then setup the middleware on your root redux configuration:
// importing libraries
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers/index';
// creating the redux store
const store = createStore(
rootReducer,
applyMiddleware(thunk)
);
Share on social media
//