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

209
Vistas
React.js fetch multiple endpoints of API

I am doing a React.js project. I am trying to pull data from an API that has multiple endpoints. I am having issues with creating a function that pulls all the data at once without having to do every endpoint separetly. The console.log gives an empty array and nothing gets display. The props 'films' is data from the parent and works fine. It is also from another enpoint of the same API. This is the code:

import { useEffect, useState } from "react";

import styles from './MovieDetail.module.css';

const MovieDetail = ({films}) => {
    const [results, setResults] = useState([]);

    const fetchApis = async () => {
        const peopleApiCall = await fetch('https://www.swapi.tech/api/people/');
        const planetsApiCall = await fetch('https://www.swapi.tech/api/planets/');
        const starshipsApiCall = await fetch('https://www.swapi.tech/api/starships/');
        const vehicleApiCall = await fetch('https://www.swapi.tech/api/vehicles/');
        const speciesApiCall = await fetch('https://www.swapi.tech/api/species/');
        const json = await [peopleApiCall, planetsApiCall, starshipsApiCall, vehicleApiCall, speciesApiCall].json();
        setResults(json.results)        
    }

    useEffect(() => {
            fetchApis();
    }, [])

    console.log('results of fetchApis', results)

    return (
        <div className={styles.card}>
            <div className={styles.container}>
                <h1>{films.properties.title}</h1>
                <h2>{results.people.name}</h2>
                <p>{results.planets.name}</p>
            </div>            
        </div>
    );
}
 
export default MovieDetail;

UPDATE

I just added the post of Phil to the code and I uploaded to a codesanbox

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

0

You want to fetch and then retrieve the JSON stream from each request.

Something like this

const urls = {
  people: "https://www.swapi.tech/api/people/",
  planets: "https://www.swapi.tech/api/planets/",
  starships: "https://www.swapi.tech/api/starships/",
  vehicles: "https://www.swapi.tech/api/vehicles/",
  species: "https://www.swapi.tech/api/species/"
}

// ...

const [results, setResults] = useState({});

const fetchApis = async () => {
  try {
    const responses = await Promise.all(Object.entries(urls).map(async ([ key, url ]) => {
      const res = await fetch(url)
      return [ key, (await res.json()).results ]
    }))

     return Object.fromEntries(responses)
  } catch (err) {
    console.error(err)
  }
}

useEffect(() => {
  fetchApis().then(setResults)
}, [])

Each URL will resolve to an array like...

[ "people", [{ uid: ... }] ]

Once all these resolve, they will become an object (via Object.fromEntries()) like

{
  people: [{uid: ... }],
  planets: [ ... ],
  // ...
}

Take note that each property is an array so you'd need something like

<h2>{results.people[0].name}</h2>

or a loop.

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