promise in jquery never executes catch block

Viewed 17

I am using a thunk action creator in redux to send a request to my Rails API via the following:

export const addProduct = (product) => (dispatch) =>
  createProduct(product)
    .then((product) => dispatch(receiveProduct(product)))
    .catch((err) => dispatch(receiveProductErrors(err.responseJSON)));

createProduct is the API utility function that sends the request to the server. I used ajax jquery to do this.

export const createProduct = (product) =>
  $.ajax({
    url: "/api/products",
    method: "POST",
    data: { product },
  });

In the code above, .catch is never evaluated, even when I try to create a request with invalid parameters. .then is always executed.

If someone could please direct me in the right direction that would be great.

1 Answers

I have fixed this issue. Just needed to throw an error so returned promise is rejected.

export const addProduct = (product) => (dispatch) =>
  createProduct(product)
    .then((product) => dispatch(receiveProduct(product)))
    .catch((err) => { 
      dispatch(receiveProductErrors(err.responseJSON));
      throw err 
    })
Related