3

I am new to react redux and I am trying to dispatch an action, but it is showing

Unhandled Rejection (Error): Actions must be plain objects. Use custom middleware for async actions

Here is my action creator:

import axios from "axios";
import { GET_CHART_DATA, GET_CHART_DATA_ERROR } from "../actionTypes";

export const getChartData = async () => {
  try {
    const { data } = await axios.get(
      "https://example.com/api"
    );
    console.log("data", data);
    return { type: GET_CHART_DATA, payload: data };
  } catch (error) {
    return { type: GET_CHART_DATA_ERROR, error: error };
  }
};

reducer:

import { GET_CHART_DATA, GET_CHART_DATA_ERROR } from "../actionTypes";

const chartDataReducer = (state = {}, action = {}) => {
  console.log("action", action);
  switch (action.type) {
    case GET_CHART_DATA:
      return { ...action.payload };
    case GET_CHART_DATA_ERROR:
      return { ...action.error };
    default:
      return { ...state };
  }
};

export default chartDataReducer;

I am dispatching the action like this:

const dispatch = useDispatch();

  useEffect(() => {
    (async () => {
      dispatch(getChartData());
    })();
  }, [dispatch]);

Store:

const store = createStore(
    rootReducer,
    composeWithDevTools(applyMiddleware(thunk))
  );

How can I correct this error?

James Z
  • 12,209
  • 10
  • 24
  • 44
  • 2
    Your action returns a function, not an object. Are you using any async middleware (i.e. Thunk middleware)? Can you share how you're creating your redux store? – Drew Reese Sep 04 '21 at 05:38
  • @DrewReese Yes I am using thunk as a middleware. I have edited the question and added the store also – Yogeshwar Chaturvedi Sep 04 '21 at 06:07
  • 1
    Does this answer your question? [React-Redux: Actions must be plain objects. Use custom middleware for async actions](https://stackoverflow.com/questions/46765896/react-redux-actions-must-be-plain-objects-use-custom-middleware-for-async-acti) – Timor Sep 04 '21 at 06:11
  • @Timor I just added await in dispatch() and it worked – Yogeshwar Chaturvedi Sep 04 '21 at 12:24
  • 1
    @YogeshwarChaturvedi happy to hear! – Timor Sep 04 '21 at 13:01

1 Answers1

1

Your getChartData is an async function and since you invoke it in your useEffect it returns a Promise, and as you see, Action must be a plain object.

You should either await the promise result before dispatching it.

const dispatch = useDispatch();

useEffect(() => {
  (async () => {
     dispatch(await getChartData());
   })();
 }, [dispatch]);

Or if you are using thunk middleware (is applied per default when using ReduxToolkit) return a thunk action in your getChartData

ecm
  • 2,583
  • 4
  • 21
  • 29
René Link
  • 48,224
  • 13
  • 108
  • 140