0

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 };
4
  • 1
    What should I do to replicate the issue on the sandbox? Commented Dec 5, 2019 at 18:43
  • Remove applyMiddleware(thunkMiddleware). I've updated the link. You can open the sandbox console(under the app view, left bottom corner), there you'll see an error. Commented Dec 5, 2019 at 19:40
  • Why do you remove applyMiddleware(thunkMiddleware) if it works with it? Commented Dec 5, 2019 at 19:41
  • @SuleymanSah, that is a great question :D. However I'm not using any async calls and want to know, why is this happening at all? Commented Dec 5, 2019 at 19:41

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

So I don't have to use dispatch for that? I mean dispatch({ type: CART_ACTIONS.CLEAR_CART }). What you are saying is, this object is passed to dispatch?
@Animus you shouldn’t use dispatch if you don’t have async action. Returning a simple object as I showed in the answer is one of the fundamentals of redux.
@Animus you are welcome, I would appreciate if you can upvote.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.