Traté de hacer 2 búsquedas de datos, una para buscar todos los productos y una vez que terminó, mapeé todos los productos y busqué cada uno de ellos por separado y los puse en una matriz. El comportamiento que no entiendo ocurre cuando intento imprimir los resultados. Si consuelo. registro toda la matriz, todo funciona bien, pero si trato de hacerlo con un solo elemento de la matriz, vuelve indefinido. No pregunte por qué necesito buscar todos los productos por separado.
Aquí está el código.
import React, { useEffect, useState } from "react"; import axios from "axios"; export const Stackoverflow1 = () => { const [data, setData] = useState(""); const [singleData, setSingleData] = useState(""); const [finished, setFinished] = useState(false); const API = `${process.env.REACT_APP_SERVER_URL}/api/products`; useEffect(() => { const fetchData = () => { axios.get(API).then((response) => { setData(response.data); setFinished(true); }); }; fetchData(); }, []); useEffect(() => { if (finished) { let list = []; data && data.map(async (item) => { const API = `${process.env.REACT_APP_SERVER_URL}/api/products/${item.id}`; axios.get(API).then((response) => { list.push(response.data); }); }); setSingleData(list); } }, [finished, data]); return ( <div> {data && singleData && data.map((item, index) => ( <div> {item.name} {console.log("inside code without index", singleData)} {console.log("inside code with index", singleData[0])} </div> ))} </div> ); }; //Console logs: // inside html without index : // [] // 0: {id: 381, name: 'Akvariumas 30l', description: 'Akvariumas 30l', price: 25.99, image_name: '16491014443.aquael-glossy-100-juodas.jpeg', …} // 1: {id: 391, name: 'Akvariumas 20l', description: 'akvariumas 20l', price: 12, image_name: '16491031283.aquarium3.jpeg', …} // 2: {id: 401, name: 'Akvariumas 30l', description: 'Akvariumas 30l', price: 150, image_name: '16491063713.aquarium4.jpeg', …} // length: 3 // [[Prototype]]: Array(0) //inside html with index undefinedDeberías usar Promise.all para esperar todas las promesas:
useEffect(() => { if (finished && data) { let list = []; Promise.all(data.map(async (item) => { const API = `${process.env.REACT_APP_SERVER_URL}/api/products/${item.id}`; const response = await axios.get(API); list.push(response.data) })).then(() => setSingleData(list)) } }, [finished, data]);