search

Home  >  Q&A  >  body text

Trouble getting specific statistics (Stats) from PokeAPI using Axios and Node.js

I have a problem, I'm trying to use the Pokemon API, but when I try to access the attack, HP, and speed stats, it shows undefined for all Pokemon! Can anyone tell me what's wrong with the API call?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

const axios = require('axios');

 

const apiPokemon = async () => {

    try {

        const pokemons = await axios

        .get('https://pokeapi.co/api/v2/pokemon?limit=50')

        const secondUrlMap = await  pokemons.data.results.map(  pokemon  => {

            return pokemon.url

        })

        const pokemonArr = await Promise.all(secondUrlMap.map(async(url) => {

            const urlResponse = await axios(url)

            return{

                id:urlResponse.data.id,

                name:urlResponse.data.name,

                height:urlResponse.data.height,

                weight:urlResponse.data.weight,

                hp:urlResponse.data.stats.find(stat => stat.name === 'hp')?.base_stat,

                attack:urlResponse.data.stats.find(stat => stat.name === 'attack')?.base_stat,

                speed:urlResponse.data.stats.find(stat => stat.name === 'speed')?.base_stat,

                types:urlResponse.data.types.map((type) => type.type.name),

                img:urlResponse.data.sprites.other['official-artwork'].front_default,

            }

        }))

        return pokemonArr

    } catch (error) {

        return ({error:error.message})

    }

}

 

module.exports =  {

    apiPokemon,

}

I have an index.js file to test API reception and this is what it returns:

1

2

3

4

5

6

7

8

const { apiPokemon } = require('./apiPokemon')

 

async function testApi() {

    const pokemons = await apiPokemon()

    console.log(pokemons)

}

 

testApi()

API structure:

P粉953231781P粉953231781384 days ago1023

reply all(1)I'll reply

  • P粉403549616

    P粉4035496162024-04-07 10:03:55

    Your current code does not properly account for the JSON structure - it is looking for the name property in the root of each object in the array. You need to use Destructuring to access the stat properties directly in the condition:

    1

    2

    3

    hp: urlResponse.data.stats.find(({stat}) => stat.name === 'hp')?.base_stat

    attack: urlResponse.data.stats.find(({stat}) => stat.name === 'attack')?.base_stat

    // etc.

    Or you can change stat.name to stat.stat.name.

    reply
    0
  • Cancelreply