Animus
Animus

Reputation: 833

Why the error "Actions must be plain objects. Use custom middleware for async actions." appears, when there are no async actions?

I was trying to figure out React deeper and stuck on this error. It didn't allow me to dispatch any actions. However, I'm not using async at all. Here you can find codesandbox of the full app.

I've added thunkMiddleware to the store, so the app will work. However I can't understand what is going on?

Here are the action creators, inside which I cloudn't dispatch. I've searched for different similar answers, and all those were connected to incorrect usage of async actions. Mine are sync:

import CART_ACTIONS from "../action_types/cartActionTypes";

function addToCart(item) {
  return dispatch => dispatch({ type: CART_ACTIONS.ADD_ITEM, item: item });
}

function removeFromCart(item) {
  return dispatch => {
    dispatch({ type: CART_ACTIONS.REMOVE_ITEM, item });
  };
}

function clearCart(item) {
  return dispatch => {
    dispatch({ type: CART_ACTIONS.CLEAR_CART });
  };
}

export const cartActions = { addToCart, removeFromCart, clearCart };

Upvotes: 0

Views: 38

Answers (1)

SuleymanSah
SuleymanSah

Reputation: 17858

You need to update your cartActions like this, if you don't want to use thunkMiddleware:

import CART_ACTIONS from "../action_types/cartActionTypes";

function addToCart(item) {
   return({ type: CART_ACTIONS.ADD_ITEM, item: item });
}

function removeFromCart(item) {
    return({ type: CART_ACTIONS.REMOVE_ITEM, item });

}

function clearCart(item) {
    return({ type: CART_ACTIONS.CLEAR_CART });
}

export const cartActions = { addToCart, removeFromCart, clearCart };

Simply, you just need to return an action which must be an object with type property and optionally a payload.

codesandbox

Upvotes: 1

Related Questions