I'm currently having a problem when trying to access an object inside an array pulled from PokeApi
Here's my fetch API which works fine :
const [gen, setGen] = useState([]);
const [loading, setLoading] = useState(false);
useEffect(() => {
setLoading(true);
axios
.get("https://pokeapi.co/api/v2/generation")
.then((res) => {
return res.data.results;
})
.then((results) => {
return Promise.all(results.map((res) => axios.get(res.url)));
})
.then((results) => {
setLoading(false);
setGen(results.map((res) => res.data));
});
}, []);
console.log(gen);
And here's a part of what I'm trying to display :
<h2 className='gen_container_inner_title'>{gen[0].name}</h2>
<h3 className='gen_container_inner_region'>{gen[0].main_region.name}</h3>
I also have another fetch from another API URL with the same method
The problem is that sometimes it works and shows the info needed but sometimes it says
gen[0] is undefined
I don't know what I'm doing wrong and why it's not working every time
Edit : the code nt working is inside this :
{loading ? (
<BarWave width="40px" height="20px" color="#cc0000" />
) : (
Your gen
array might not have items when the first time it renders.
You can use optional chaining operator(?.) along with nullish coalescing operator(??) to get rid of the errors.
<h2 className='gen_container_inner_title'>{gen?.[0]?.name ?? ""}</h2>
<h3 className='gen_container_inner_region'>{gen?.[0]?.main_region?.name ?? ""}</h3>