No estoy seguro de cómo hacer esto. Obtengo de 1 URL para obtener una matriz de objetos como este:
[{name: 'apple', url: 'appleURL'}, {name: 'orange', 'orangeURL', ...}]luego mapee a través de cada URL para obtener datos, los datos devueltos para cada elemento tienen otra URL... como esta:
[{name: 'apple', colors: ['green', 'red'], type: 'http://URL-that-needs-fetching'},{...etc}]esto es lo que tengo, y funciona pero es extremadamente lento...
useEffect(() => { const fetchFruit = async () => { setLoading(true); const fruitResponse = await fetch(fruitPath); const fruitJson: Fruit = await fruitResponse.json(); const fruitDetails = await Promise.all( fruitJson.results.map(async (f: FruitURLs) => { const fDetails = await fetch(f.url); const json: FruitDetails = await fDetails.json(); return json; }) ); const getFruitDescriptions = await Promise.all( fruitDetails.map(async (item: FruitDetails, index: number) => { const fruitType = await fetch(item.type.url); const json: FruitInfo = await fruitType.json(); return json; }) ); let full: FruitDetails[] = fruitDetails; for (let index = 0; index < fruitDetails.length; index++) { full[index].fruitInfo = getFruitDescriptions[index]; } setFruitDetails(full); setLoading(false); }; fetchFruit(); }, []);Soy nuevo en el uso de promesas y no estoy 100% seguro con ellas, también nuevo en TS y nativo de reacción, así que disculpas si hay errores aquí ...
El problema es que al usar await( await() dentro Promise.all() , está resolviendo las búsquedas en lugar de que sucedan en paralelo y devolviéndolas envueltas en una promise .
Puedes tomar una referencia:
const fetchFruit = async () => { const fruitResponse = await fetch(fruitPath); const fruitJson: Fruit = await fruitResponse.json(); const fruitDetails = await Promise.all( fruitJson.results.map(async (f: FruitURLs) => fetch(f.url)) ); const getFruitDescriptions = await Promise.all( fruitDetails.map(async (item: FruitDetails, index: number) => fetch(item.type.url) ) ); const [fruitDetailsAsJson, getFruitDescriptionsAsJson] = Promise.all([ fruitDetails.map(async (f) => f.json()), getFruitDescriptions.map(async (f) => f.json()), ]); const full = fruitDetailsAsJson.map((fruit, index) => ({ ...fruit, fruitInfo: getFruitDescriptionsAsJson[index], })); setFruitDetails(full); setLoading(false); };Utilice este recurso para conocer las mejores prácticas.