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.
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.
CodePudding user response:
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>
))}
</>
)
}