Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

205
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda