react-redux Error: Actions must be plain objects. Use custom middleware for async actions

Viewed 1861

I have a very simple code for incrementing and decrementing when + or - buttons are pressed. but whenever I press the buttons, I receive the error. I've been working on it for about 4 hours and can't find out why. I'm pretty sure that I'm not doing any async actions and my actions are returning JavaScript objects

actions code:

export const increment = () => {
    return { type: 'INCREMENT' }
}

export const decrement = () => {
    return { type: 'DECREMENT' }
}

reducer code:

export default function counterReducer(state = 0, action) {
    switch (action.type) {
      case 'INCREMENT':
        return state + 1
      case 'DECREMENT':
        return state - 1
      default:
        return state
    }
  }

app component code:

import React from "react";
import {decrement, increment } from "./actions";
import { useSelector, useDispatch } from "react-redux";
export default function App() {
  const counter = useSelector((state) => state.counter);
  const dispatch = useDispatch();
  return (
    <div>
      <button onClick={() => dispatch(increment)}>+</button>
      <button onClick={() => dispatch(decrement)}>-</button>
      <p>{counter}</p>
    </div>
  );
}

Much appreciated.

3 Answers

In Redux, actions are objects. You have to execute actions functions into dispatch: dispatch(increment) could be dispatch(increment())

You are dispatching action creator functions not the actions

The increment and decrement functions are called action creators. They return the action object.

You should call the action creator function for dispatching an action.

<button onClick={() => dispatch(**increment()**)}>+</button>

That problem is solved by using a middleware like redux-thunk or saga in the store configuration.

import { createStore, applyMiddleware } from "redux";

import rootReducer from "../reducers";
import thunk from "redux-thunk";

//Applying redux-thunk solves the problem
//Actions must be plain objects. Use custom middleware for async actions.

export const store = createStore(rootReducer, applyMiddleware(thunk));
Related