I'm working with React jS and fetching data from pokeapi.
Here's the data structure from the api (goes to number 5) :
stats
0
base_stat
effort
stat
name
url
1
base_stat
effort
stat
name
url
Here's my code :
const minHp = pokemon?.stats[0]?.base_stat * 2 + 110;
const maxHp = pokemon?.stats[0]?.base_stat * 2 + 204;
<td className='pokemon_stats_table_row_element'>
{minHp}
</td>
<td className='pokemon_stats_table_row_element'>
{maxHp}
</td>
When I load the page there is an error that says that 'pokemon.stats is undefined' and I don't understand why it doesn't works because the path is correct and existing (i'm displaying other data from the 'stats' array and it works fine.
You need to use the optional chaining ? operator also when indexing into the stats object, because that property can return undefined, like this:
const minHp = pokemon?.stats?.[0]?.base_stat * 2 + 110;
const maxHp = pokemon?.stats?.[0]?.base_stat * 2 + 204;