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

116
Visualizações
Promise only resolves correctly on page refresh

I am playing around with an API that gets a list of Pokemon and corresponding data that looks like this.

export function SomePage() {
const [arr, setArray] = useState([]);

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


  function fetchSomePokemon() {
    fetch('https://pokeapi.co/api/v2/pokemon?limit=5')
     .then(response => response.json())
     .then((pokemonList) => {
       const someArray = [];
     pokemonList.results.map(async (pokemon: { url: string; }) => {
       someArray.push(await fetchData(pokemon))
     })
     setArray([...arr, someArray]);
    })
   }

   async function fetchData(pokemon: { url: string; }) {
    let url = pokemon.url
     return await fetch(url).then(async res => await res.json())
    }

    console.log(arr);

  return (
      <div>
      {arr[0]?.map((pokemon, index) => (
          <div
            key={index}
          >
            {pokemon.name}
          </div>
        ))
      }
      </div>
  );
}

The code works(kind of) however on the first render the map will display nothing even though the console.log outputs data. Only once the page has been refreshed will the correct data display. I have a feeling it's something to do with not handling promises correctly. Perhaps someone could help me out. TIA

Expected output: Data populated on initial render(in this case, pokemon names will display)

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

The in-build map method on arrays in synchronous in nature. In fetchSomePokemon you need to return a promise from map callback function since you're writing async code in it.

Now items in array returned by pokemonList.results.map are promises. You need to use Promise.all on pokemonList.results.map and await it.

await Promise.all(pokemonList.results.map(async (pokemon: { url: string; }) => {
       return fetchData.then(someArray.push(pokemon))
     }));
about 4 years ago · Juan Pablo Isaza Relatório

0

On your first render, you don't have the data yet, so arr[0] doens't exist for you to .map on it, so it crashes. You need to check if the data is already there before mapping.

Using optional chaining, if there's no data it will not throw an error on your first render and it will render correctly when the data arrive and it re-renders.

...
  return (
    <div>
      {arr[0]?.map((pokemon, index) => (
        <div key={index}>{pokemon.name}</div>
      ))}
    </div>
  );
}
about 4 years ago · Juan Pablo Isaza Relatório

0

in

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

[] tells react there is no dependencies for this effect to happen,

read more here https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects

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