bigcommerce / storefront-data-hooks

Hooks for React Storefront UI Components
MIT License
166 stars 36 forks source link

Uncatchable error from useUpdateItem #122

Closed leffot closed 2 years ago

leffot commented 2 years ago

Using

Issue When a user tries to increment a product’s inventory beyond the maximum available, an error is thrown: Uncaught (in promise) Error: An unexpected error ocurred with the Bigcommerce API.

Of course, we expect an error to be returned in this instance, since the user should not be able to add more inventory to their cart, as they’ve already hit the limit.

But what’s odd is that this error cannot be caught, which means we can’t pass the error along to the user.

Our Incrementer component looks something like this:

export default function Incrementer({ item, quantity }) {
    const updateItem = useUpdateItem(item, {
        include: [
            'line_items.physical_items.options',
            'line_items.digital_items.options',
        ],
    })

    const updateQty = async newValue => {
        try {
            await updateItem({
                quantity: parseInt(newValue),
            })
        } catch (error) {
            console.log(error)
        }
    }

    return (
        <ActionButton
            caption='Increase Quantity:'
            onClick={() => updateQty(quantity + 1)}
        >
            <ChevronUp />
        </ActionButton>
    )
}

The call to updateItem is wrapped in a try...catch, so conceivably the error should be caught. Is there some other approach we’re supposed to take here?

And in fact it appears that updateItem doesn’t even return a promise, because if we try this:

const res = updateItem(...)
console.log(res)

Then res is immediately logged as undefined, and the error is thrown a few seconds later. Thoughts?

jorgemasta commented 2 years ago

Thanks for the detailed issue @leffot! 🙌

I have debugged this and looks like it's related to this debounce https://github.com/bigcommerce/storefront-data-hooks/blob/abbe17a37d36e57ad1183d230d04ebbbb6dfefa0/src/cart/use-update-item.tsx#L54

What's happening?

  1. A product has a stock limit
  2. If the stock is exceeded when using the useUpdateItem, it will fail
  3. Because we have that debounce, the error is not thrown on the first failed request.
  4. It's throwing an error on the next request

How to solve it?

I would remove it from the library and let the users decide if they want a debounce or not. (cc @jivewise)

leffot commented 2 years ago

Thanks for the quick reply @jorgemasta! That makes sense. I appreciate you looking into it.

jorgemasta commented 2 years ago

The latest beta release includes this fix. You can try it running yarn add @bigcommerce/storefront-data-hooks@beta.

Closing because it will be included in the next release.

leffot commented 2 years ago

Thanks @jorgemasta. Works like a charm!