• Register
0 votes
1.3k views

Problem :

Facing below error:

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

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

export function bindAllComments(postAllId) {
  return API.fetchComments(postAllId).then(comments => {
    return {
      type: BIND_COMMENTS,
      comments,
      posAlltId
    }
  })
}

 

7 5 2
3,870 points

Please log in or register to answer this question.

2 Answers

0 votes

Solution :

I had also faced the similar issue in the recent past. I did lot of research on it and found the solution on it. This is the very common problem with the people getting started.

You must dispatch after async request ends.

This program would work:

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

 

OR

Make use of the Arrow functions it improves the readability of code. No need to return anything in the API.fetchComments, Api call is asynchronous when the request is completed then will get your response, there you have to just dispatch type and data.

Below code does the same job by making use of the Arrow functions.

export const bindAllComments = postAllId => {
  return dispatch => {
    API.fetchComments(postAllId).then(comments => {
      dispatch({
        type: BIND_COMMENTS,
        comments,
        postAllId
      });
    });
  };
};

 

9 7 4
38,600 points
0 votes

Solution:

You should dispatch after the async request ends.

Follow the below code:

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

 

You can't use fetch in actions without middleware.

Explanation:

Actions must be plain objects. You can use a middleware like redux-thunk or redux-saga to do fetch and then dispatch another action.

Follow the example of async action using redux-thunk middleware.

export function checkUserLoggedIn (authCode) {
 let url = `${loginUrl}validate?auth_code=${authCode}`;
  return dispatch => {
    return fetch(url,{
      method: 'GET',
      headers: {
        "Content-Type": "application/json"
      }
      }
    )
      .then((resp) => {
        let json = resp.json();
       if (resp.status >= 200 && resp.status < 300) {
          return json;
        } else {
          return json.then(Promise.reject.bind(Promise));
        }
      })
      .then(
        json => {
          if (json.result && (json.result.status === 'error')) {
            dispatch(errorOccurred(json.result));
            dispatch(logOut());
          }
          else{
            dispatch(verified(json.result));
          }
        }
      )
      .catch((error) => {
        dispatch(warningOccurred(error, url));
      })
  }
}

 

10 6 4
31,120 points

Related questions

0 votes
1 answer 3 views
3 views
Problem: 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 } }) }How to achieve that?
asked 4 days ago anika11 32k points
0 votes
1 answer 2 views
2 views
Problem: So I have wasted 5 hours on this. I have a redux thunk action like this: export const fetchUser = () => async (getState, dispatch) => { if (getIsFetching(getState().user)) { return Promise.resolve(); } dispatch(fetchUserRequest()); try ... for that, why does it keep bugging me? NOTE: fetchUserRequest(), fetchUserSuccess() and fetchUserFailure() all return simple, plain redux actions.
asked Apr 25 muktaa 34.4k points
0 votes
1 answer 2 views
2 views
Problem: I am getting above error while fetching some data from the API. Following is the code of the action creator where I am trying GET the data: import { FETCH_USER } from './types'; import axios from 'axios'; export const fetchUser = () => async dispatch ... payload: res }); }; Also when I am debugging in the code editor, console is giving me below error: SyntaxError: Unexpected token import
asked 2 days ago anika11 32k points
0 votes
1 answer 40 views
40 views
Problem: HELP! I need help understanding this error :Local package.json exists, but node_modules missing, did you mean to install?.
asked Mar 6 Wafa Abu Yousef 6.1k points
0 votes
1 answer 4.2K views
4.2K views
Problem : I am trying to start the Redux application I just cloned from the GitHub repository. I tried to run it with the below command npm start But I am getting below error > react-redux@1.0.0 start /home/workspace/assignment > webpack-dev-server --config ./ ... output above. npm WARN Local package.json exists, but node_modules missing, did you mean to install? How can I fix the above error?
asked Jan 20, 2020 jwilliam 3.9k points
0 votes
1 answer 2 views
2 views
Problem: I am trying to call an api and I get the error "Unhandled promise rejection: Error: Request failed with status code 500". I dunno how did I get the error.I put the api call in componentDidMount. I am not sure whether the error comes from the redux ... no-cache","cache- control":"no-cache"},"_subscriptions": [],"responseURL":"https://smp.ums.edu.my/api/result/GetListOfKodSesiSem"}}}
asked 2 days ago anika11 32k points
1 vote
1 answer 89 views
89 views
Problem: I am working on React project where I am trying to wrap text around an image and I understand that this style="float: left" is html 5. However if I use the following code: <div className="container"> <img src={myImageSource} alt="swimmer" height="300" width="300" align="left" /> <p> This is where the other text goes about the swimmer</p> </div> It works! Why can't I use style in React?
asked Mar 22 Sabbir Hossain 14.6k points
0 votes
1 answer 45 views
45 views
Problem syntax error: adjacent jsx elements must be wrapped in an enclosing tag.
asked Feb 11 charles mathews 5.5k points
0 votes
1 answer 5 views
5 views
Problem: I have a carousel file in which I want to get index.js and build block.build.js, so my webpack.config.js is: var config = { entry: './index.js', output: { path: __dirname, filename: 'block.build.js', }, devServer: { contentBase: './Carousel ... ./index.js Module build failed: Error: Plugin/Preset files are not allowed to export objects, only functions. Does anyone know how to solve this?
asked 5 days ago muktaa 34.4k points