Hola, estoy haciendo un programa de reacción SPA. Tengo una pregunta.
Quiero saber cómo puedo usar estos datos JSON HackNews
const [storyIds, setStoryIds] = useState([]); const list = []; useEffect(() => { Top_API().then((res) => { this.res = res.data.slice(0, 3); this.res.forEach((ele) => { axios .get("https://hacker-news.firebaseio.com/v0/item/" + ele + ".json") .then((res) => { list.push({ id: res.data.id, title: res.data.title, url: res.data.url, user: res.data.by, score: res.data.score }); setStoryIds(list); }); }); }); }, []);este es mi código quiero imprimir estos datos api Imprimo datos JSON como este
{JSON.stringify(storyIds[0])}Este código funciona bien. Sin embargo, desde el arreglo storyIds[1], no es visible en la pantalla. Comprobé que se emitía desde la consola.
Y cuando voy a una página diferente, si envío el contenido de mi matriz de código, se produce un error que indica que no se puede encontrar la matriz cuando regresa a la página. ex)
{JSON.stringify(storyIds[0].title)}Si escribe como el código anterior, se produce un error de que la matriz no está definida.
He estado tratando de resolver esta situación durante tres días sin una solución adecuada.
El código que imprimes en pantalla es el siguiente.
<div className="n1"> <a href={JSON.stringify(storyIds[0])}> {JSON.stringify(storyIds[0])} </a> <br /> by: {JSON.stringify(storyIds[0])} </div> <div className="n2">{JSON.stringify(storyIds[1])}</div> <div className="n3">{JSON.stringify(storyIds[2])}</div> </div>los datos se ven como
[{"id":30186326,"title":"Facebook loses users for the first time","url":"https://www.washingtonpost.com/technology/2022/02/02/facebook-earnings-meta/","user":"prostoalex","score":994},{"id":30186894,"title":"In second largest DeFi hack, Blockchain Bridge loses $320M Ether","url":"https://blockworks.co/in-second-largest-defi-hack-ever-blockchain-bridge-loses-320m-ether/","user":"CharlesW","score":400}]¿Cómo puedo imprimir esta respuesta API en mi pantalla?
Debe usar async await await con Promise.all para esperar la respuesta de la API
useEffect(() => { Top_API().then(async (res) => { this.res = res.data.slice(0, 5); Promise.all( this.res.map(async (r) => { return await axios.get( "https://hacker-news.firebaseio.com/v0/item/" + r + ".json" ); }) ).then((resolved) => { resolved.map((resolve) => { list.push({ id: resolve.data.id, title: resolve.data.title, url: resolve.data.url, user: resolve.data.by, score: resolve.data.score }); }); setStoryIds(list); }); }); }, []);El problema con su código es que está restableciendo el estado de storyIds al único elemento que carga la llamada GET en cada ciclo de ciclo.
Prueba a cambiarlo así:
const [storyIds, setStoryIds] = useState([]); useEffect(async () => { const list = []; let apiResponse = await Top_API(); apiResponse = apiResponse.data.slice(0, 3); apiResponse.forEach(async (ele) => { const { data } = await axios.get( 'https://hacker-news.firebaseio.com/v0/item/' + ele + '.json' ); const { id, title, url, by, score } = data; list.push({ id, title, url, user: data.by, score }); }); setStoryIds(list); }, []);