• Register
0 votes
909 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 3K views
3K 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 1.6K views
1.6K views
Problem : I have a carousel file in which I want to get my index.js and build the block.build.js, and my webpack.config.js But I face below error message: ERROR in ./index.js Module build failed: Error: Plugin/Preset files are not allowed to export objects, only functions. Does anyone know the solution on this?
asked Jan 18, 2020 jwilliam 3.9k points
0 votes
1 answer 2.3K views
2.3K views
Problem : Facing following strange issue input is a void element tag and must neither have `children` nor use `dangerouslysetinnerhtml`.
asked Nov 13, 2019 peterlaw 6.9k points
0 votes
2 answers 93 views
93 views
Problem : I am using the reactjs. When I run my code below my browser says: Uncaught TypeError: Super expression must either be null or a function, not undefined Any clues at all as to what is wrong with my code? First the line used to compile the code as below : ... var React = require('react'); class HelloMessage extends React.Component {   render() {     return <div>Hello World</div>;   } }
asked Jan 23, 2020 jwilliam 3.9k points
0 votes
1 answer 950 views
950 views
Problem : I am using the reactjs. When I try to run my code the browser says as below: Uncaught TypeError: Super expression must either be null or a function, not undefined The line used to compile my code: browserify -t reactify -t babelify examples/temp.jsx -o examples/public ... Component { render() { return <div>Hello World !! </div>; } } Does anyone have any idea on the solution for my issue?
asked Dec 7, 2019 alecxe 7.5k points
0 votes
1 answer 412 views
412 views
Problem : I have created the new React application by just using create-react-app and I amtrying to write a unit test to the component named "MessageBox" that I have created in the application. I have also added the file under my 'src' folder named 'setupTests.js ... an adapter, you should call msenzyme.configure({ > adapter: new Adapter() }) Does someone know how can I solve this problem?
asked Dec 19, 2019 alecxe 7.5k points
0 votes
2 answers 236 views
236 views
Problem : I am trying to learn React JS. I have written a code for component . I also have the data that I get from a Data Base, and whose current state (myDB) I dispatch.I am trying to use data from myDB object and then want to display some of the ... a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons How to fix this issue ?
asked Feb 22, 2020 mphil 2.3k points
0 votes
4 answers 19 views
19 views
Redux Interview Questions & Answers for experienced and fresher students. It will be great to hear from your side. These interview questions will help you to ace the job interview efficiently Thank-you!
asked Dec 3, 2020 justin t 690 points
0 votes
1 answer 336 views
336 views
Problem: I have recently started learning about React, Babel, JSX and JS. Now I am receiving an error from a babel if I tried to compile my JSX code into a JS code. Please find the error: &ldquo;Jsx value should be either an expression or a quoted jsx text.&rdquo ... out in my searching on interenet that prop values should be passed only between {}, but adding these to my code did not help me.
asked Aug 13, 2020 Raphael Pacheco 4.9k points