Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

132
Vistas
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?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda