This is fetching from Pokemon API which response with an array that I want to pass useState variable initialized as empty array with setValue function.
React component is below:
import React, { useState, useEffect } from "react";
export default function Pokemones() {
const [pokemons, setPokemons] = useState([]);
useEffect(() => {
async function fetchData() {
// Call fetch
const res = await fetch("https://pokeapi.co/api/v2/pokemon/");
// Pull out the data
const json = await res.json();
// Save the data to array
console.log(json.results);
}
fetchData();
}, []);
return (
<ul>
{pokemons.map((pokemon) => (
<li>
<p>Name = {pokemon.name}</p>
<p>URL = {pokemon.name}</p>
</li>
))}
</ul>
);
}
I tried directly set setPokemons(json.results); or by json.results.map, received same error.
I did other tries but I got similar errors
// atfet console.log and before fetchData function
let pok = [];
json.results.map((p) => (pok = [...pok, p]));
console.log(pok);
setPokemons(pok);
}
The error received on consola is:
Uncaught Error: Objects are not valid as a React child (found: object with keys
{name, url}). If you meant to render a collection of children, use an array instead.
I guess that array is not passing to variable pokemons but I am able to see in console the array. what part is that I am missing.
thanks
>Solution :
I hope this helps.
import React, { useState, useEffect } from "react";
export default function Pokemones() {
const [pokemons, setPokemons] = useState([]);
useEffect(() => {
async function fetchData() {
// Call fetch
const res = await fetch("https://pokeapi.co/api/v2/pokemon/");
// Pull out the data
const json = await res.json();
// Save the data to array
console.log(json.results);
setPokemons(json.results);
}
fetchData();
}, []);
return (
<ul>
{pokemons.map((pokemon, index) => {
return <li key={index}>
<p>Name = {pokemon.name}</p>
<p>URL = {pokemon.name}</p>
</li>
})}
</ul>
);
}