Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 416
Yogeshwar Chaturvedi Avatar asked Feb 02 '26 18:02

Yogeshwar Chaturvedi


1 Answers

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

like image 136
René Link Avatar answered Feb 05 '26 12:02

René Link