reactjsreduxreact-redux

React-Redux: Actions must be plain objects. Use custom middleware for async actions


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

I wanted to add comments with every posts. So when fetch posts are run I want to call fetch comment API for all post.

export function bindComments(postId) {
  return API.fetchComments(postId).then(comments => {
    return {
      type: BIND_COMMENTS,
      comments,
      postId
    }
  })
}

Solution

  • You have to dispatch after the async request ends.

    This would work:

    export function bindComments(postId) {
        return function(dispatch) {
            return API.fetchComments(postId).then(comments => {
                // dispatch
                dispatch({
                    type: BIND_COMMENTS,
                    comments,
                    postId
                });
            });
        };
    }