Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

92
Views
making a post request inside mapDispatchToProps in react-redux

I'm trying to make a post request inside a function whenever i click on a button. here is the code of the button

<Button onClick={handleClick}>Add to Cart</Button>

and here is the `handleClick funcion:

const handleClick = (event) => {

        event.preventDefault(); 
        props.postCart(itemData.product_name, itemData.product_price);
    }

and here i showcase the code of mapDispatchToProps function:

const mapDispatchToProps = dispatch => {

    return {

        postCart: (productName, productPrice) => dispatch(postAddToCart(productName, productPrice))
    }
}

finally the code of postAddToCart:

export const postAddToCart = (productName, productPrice) => {

    const email = sessionStorage.getItem('email');

    return (dispatch) => {

        dispatch(productName, productPrice);
        //REST API endpoint
        axios.post('http://localhost:8000/api/auth/add-to-cart', {

            email:email, 
            
        })
        .then(resp => {

            dispatch({

                type: actionTypes.ADDED_TO_CART, 
                status: resp.status
            });
        })

        .catch(resp => {

            dispatch({

                type: actionTypes.ADDED_TO_CART, 
                status: "FAILED"
            });
        })

    }

}

But whenever i click the button Add to cart i get the following error:

Error: Actions must be plain objects. Use custom middleware for async actions. knowing that i'm using the redux-thunk middleware.

Can you please tell me what's the problem and how can i fix it ? thank you ^^. if i missed something tell me in comments to add it ^^

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Your function postAddToCart() returns a "dispatcher", i.e. a function that expects dispatch as an argument.

The error is that you are trying to dispatch this "dispatcher", instead of an "action":

// wrong: calling 'dispatch()'
postCart: (productName, productPrice) => dispatch(postAddToCart( ... ))

// correct: calling the returned dispatcher and pass 'dispatch' as argument
postCart: (productName, productPrice) => postAddToCart( ... )(dispatch)
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!