Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Array data not mappable even though console shows data

I am having a small issue that I cannot seem to get right.
I am fetching data from Pokeapi to get some pokemon back, then iterating through that data in order to trigger another fetch request to bring back the associated data with a given pokemon.

I want to push this data to an array so that I can fire off this request as the application loads and save the data to storage so no new requests have to be made. However… (Which I have not done yet btw)

I console.log the results and the data is there, but when trying to map the data out, nada.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Please see my attempt below:

export function SomeComponent() {
  let arr = [];


  async function fetchPokemon() {
  const pokemon = await fetch('https://pokeapi.co/api/v2/pokemon?limit=10')
   .then(response => response.json())
  for await (const x of pokemon.results.map(async (result) => await fetch(result.url)
  .then(response => response.json()))) {
    arr.push(x);
    }
  }

  fetchPokemon();
  console.log(arr)

return (
  <>
    {arr.map((pokemon) => (
       <p>
         {pokemon.name} 
       </p>
    ))}
  </>
 )
}

My best guess is that the console is displaying live results and that they data is not actually populated yet?

I would like to see the pokemon names displayed in the

tag.

>Solution :

In react we should use state to store data and useEffect to do side effect actions like fetching data :

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


  async function fetchPokemon() {
  const pokemon = await fetch('https://pokeapi.co/api/v2/pokemon?limit=10')
   .then(response => response.json())
  for await (const x of pokemon.results.map(async (result) => await fetch(result.url)
  .then(response => response.json()))) {
    setArray([...arr, x]);
    }
  }
useEffect(() => {fetchPokemon()}, []}

return (
  <>
    {arr.map((pokemon) => (
       <p>
         {pokemon.name} 
       </p>
    ))}
  </>
 )
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading