0

Within my state, I have an array of objects that have a few descriptive properties, a quantity, and a unique id. The data within this object comes back from an API response, and within my action creator, I check the state to see if it exists already and if so dispatch an increment action for my reducer. This is what my action creator looks like:

export const getProductDetails = upc => (dispatch, getState) => {
const state = getState();
const products = state.table.products;
if (_find(products, upc) !== undefined) {
  dispatch({ type: INCREMENT_QUANTITY, payload: upc });
} else {
axios
  .post(<--POST TO ENDPOINT-->) }
  })
  .then(res => {
    dispatch({ type: POST_UPC, payload: res.data });
  })
  .catch(err => {
    errorHandler(dispatch, err.response, AUTH_ERROR);
  });
 }
};

My reducer for this case looks is structured as so:

case INCREMENT_QUANTITY:
  return {
    ...state,
    products: state.products.map(product => {
      action.payload === product.upc
        ? { ...product, quantity: product.quantity + 1 }
        : product;
    })
  };

I based this reducer logic from this this excellent response, but for some reason when the action is dispatched, the duplicate product is overwritten as null instead of incrementing the quantity as expected. I'm still trying to learn redux right now, so forgive my ignorance. Ideally, I'd like to avoid bringing in a library or package just to increment a value. What exactly am I missing within my reducer?

Christian Todd
  • 226
  • 1
  • 3
  • 14

1 Answers1

3

You're not returning anything in your map callback, you're creating a block thus you don't get the intended result. Instead, omit the brackets { … }:

products: state.products.map(product => 
  action.payload === product.upc
    ? { ...product, quantity: product.quantity + 1 }
    : product;
);

This will use arrow function syntax to implicitly return the result of the ternary operator.

Andrew Li
  • 55,805
  • 14
  • 125
  • 143
  • Perfect! I knew I was missing something small within that map function. So now the object within the array doesn't become `null`, but the quantity field stays static across multiple dispatched calls to increment that field. Is there something I'm missing there as well? – Christian Todd Jul 09 '17 at 09:38
  • @ChristianTodd Perhaps you meant `action.payload.upc`? Could your provide the dispatched action? – Andrew Li Jul 09 '17 at 14:14
  • I updated my original question to contain my entire action creator. Hopefully that will be more clear. – Christian Todd Jul 09 '17 at 16:08
  • @ChristianTodd That might be beyond the scope of the initial question. Maybe asking a new one with all the details will get fresh eyes and an exact answer. – Andrew Li Jul 09 '17 at 17:34