Tengo una función con try catch dentro. Llamo a la API sobre la respuesta. Esta respuesta me devuelve un objeto Result con algunos datos. Pero a veces me gustaría volver a intentar la función si no tengo nombre y tengo bundle_id.
Me gustaría volver a intentar estas funciones como máximo 3 veces. Si no hay resultado, me gustaría arrojar un error.
Tengo algo como esto, pero no funciona para mí.
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; } };¿Usted me podría ayudar?
Podría usar un estado para rastrear el conteo de intentos.
[retry_count, setRetryCount] = useState(0); useEffect(() => { if (retry_count < 3) { // .... put fetch code here } }, [retry_count]) Incremente el retry_count cada vez colocándolo en el bloque catch dentro de su función de búsqueda
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]); Con useEffect , esto significa que cada vez que se incrementa retry_count (en este caso ocurre un error), se realizará la función dentro de la llamada useEffect .