karo-s
karo-s

Reputation: 414

How can I retry a function with try/catch in react js?

I have a function with try catch inside. I call to the API about response. This response returns me a Result object with some data. But sometimes I'd like to retry the function if I have no name and have bundle_id.

I'd like to retry this functions max 3 times. If no result, I'd like to throw an error.

I have sth like this, but it doesn't work for me.

const getECommerceProduct = async ({
    item,
    getParent = false,
    variantInfo,
}) => {
    if (!item.id) return null;
    let retryCounter = 0;
    try {
        const response = await getEvaService(Core.GetProductDetail, {
            ID: item.id,
        });
        const itemResponse = response?.Result;
        if (!itemResponse) return null;

        // Retry the function if the item has no name and has a bundle product.
        // The bundle product will give back more information about the product.
        const retry = !!itemResponse.bundle_id && !itemResponse.product_name;
        if (retry && !getParent && retryCounter <= 3) {
            retryCounter += 1;
            return getECommerceProduct({
                item: {
                    id: itemResponse.bundle_id,
                    quantity: item.quantity,
                    variantInfo,
                },
                getParent: true,
            });
        }
        return transformProductToECommerce(itemResponse, item);
    } catch (e) {
        console.error(e);
        return null;
    }
};

Could you help me?

Upvotes: 0

Views: 2900

Answers (1)

Mohd Yashim Wong
Mohd Yashim Wong

Reputation: 266

You could use a state to track the attempt count.

[retry_count, setRetryCount] = useState(0);


useEffect(() => {
   if (retry_count < 3) {
      // .... put fetch code here
   }
}, [retry_count])

Increment the retry_count every time by putting it in the catch block within your fetch function

    React.useEffect(() => {
        const getECommerceProduct = async ({ item, getParent = false, variantInfo }) => {
            if (!item.id) return null;

            const response = await getEvaService(Core.GetProductDetail, {
                ID: item.id,
            });

            const itemResponse = response?.Result;
            if (!itemResponse) return null;

            return transformProductToECommerce(itemResponse, item);
        };

        if (retry_count < 3) {
            getECommerceProduct().catch((e) => {
                console.error(e);
                setRetryCount(retry_count + 1);
                return null;
            });
        }
    }, [retry_count]);

With the useEffect, this means that every time the retry_count is incremented (in this case an error happens), the function within the useEffect call will be performed.

Upvotes: 1

Related Questions