JavaScript - Ayuda al consumir api de pokeapi

 
Vista:
sin imagen de perfil
Val: 37
Ha disminuido su posición en 2 puestos en JavaScript (en relación al último mes)
Gráfica de JavaScript

Ayuda al consumir api de pokeapi

Publicado por Pepe (13 intervenciones) el 10/08/2020 20:16:41
Hola buenas estoy practicando fetch en javascript y me he atascado a la hora de mostrar la imagen del pokemon.

Consumo la api de pokeapi, hago la llamada a esta URL https://pokeapi.co/api/v2/pokemon?limit=50&offset=100,
el problema que se me presenta es que para mostrar la imagen del pokemon, tengo que hacer una llamada a otra api https://pokeapi.co/api/v2/pokemon/${idPokemon} en la que le paso el id del pokemon, creo que es el id, pero no estoy muy seguro.
Me he atascado y no soy capaz de ir a la segunda llamada para pintar la imagen del pokemon.
Si alguien más experimentado me podría ayudar.
Dejo mi código js y html. Por si véis dónde está el problema.
Dejo las urls a los json que quiero mostrar
https://pokeapi.co/api/v2/pokemon?limit=50&offset=100
https://pokeapi.co/api/v2/pokemon/101/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
</head>
<body>
<table class="table table-dark">
  <thead>
    <tr>
      <th scope="col">ID</th>
      <th scope="col">Nombre Pokemon</th>
      <th scope="col">Imagen Pokemon</th>
    </tr>
  </thead>
  <tbody id="contenido">
  </tbody>
</table>
<script type="text/javascript" src="consumoApiFetch.js"></script>
</body>
</html>

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
const URLAPI = 'https://pokeapi.co/api/v2/pokemon?limit=50&offset=100',
CONTENIDO = document.getElementById('contenido'),
CONTENIDONOMBRE = document.getElementById('contenidoNombre');
 
//Poner url api por parámetros
const setUrlApi = (cantidadPokemon,desde) =>{
    let url = '';
    if(!isNaN(cantidadPokemon) && !isNaN(desde)){
    url = 'https://pokeapi.co/api/v2/pokemon?limit='+  cantidadPokemon +'&offset='+desde
    }else{
        url = 'https://pokeapi.co/api/v2/pokemon?limit=25'
    }
    return url
}
 
// lista pokemon
const getPokemons = () => {
                fetch(URLAPI)
                   .then( response => response.json())
                   .then((datos) => {
                       console.log(datos);
                       datos.results.forEach(e => {
                           showData(e);
                           let idPokemon = showData(e);
                           fetch(`https://pokeapi.co/api/v2/pokemon/${idPokemon}`)
                           .then(res => res.json())
                           .then(img =>{
                                setImgPokemon(img);
                           })
                           .catch(error => {console.log('Error segunda petición',error)})
 
                       });
                   })
                   .catch(error => {
                       console.log('Error primera petición',error)
                   })};
 
//Mostrar lista datos pokemon
const showData = data => {
    let count =1;
    let idPokemon = data.url.slice(-4);
    idPokemon = idPokemon.replace('/','');
    const pokemon = `
    <tr>
    <th scope="row">${idPokemon}</th>
    <td id="contenidoNombre">${data.name}</td>
    `;
    CONTENIDO.insertAdjacentHTML('beforeend', pokemon);
    return idPokemon;
}
 
const setImgPokemon = imgPokemon =>{
    let img = imgPokemon.sprites.front_default;
    const showimg= `
            <td><img class = "img-fluid img-thumbnail rounded " src ="${img}"></td>
            </tr>
                `;
    CONTENIDONOMBRE.insertAdjacentHTML('beforeend', pokemon);
 
}
 
getPokemons();
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
sin imagen de perfil
Val: 37
Ha disminuido su posición en 2 puestos en JavaScript (en relación al último mes)
Gráfica de JavaScript

Ayuda al consumir api de pokeapi

Publicado por Pepe (13 intervenciones) el 10/08/2020 20:48:37
Ya descubrí el error CONTENIDONOMBRE.insertAdjacentHTML('beforeend', pokemon); no me detecta el td con el id contenidonombre, por que lo genero de forma dinámica, si a alguien se le ocurre una forma de coger la referencia de este td. e insertar la img
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil
Val: 37
Ha disminuido su posición en 2 puestos en JavaScript (en relación al último mes)
Gráfica de JavaScript

Ayuda al consumir api de pokeapi

Publicado por pepe (13 intervenciones) el 10/08/2020 22:11:40
ya lo solucione problemas a la hora de coger referencia de la api
solo tuve que poner
1
showData(e, img.sprites.front_default);
agregar el td con la imagen y ponerlo en el segundo fetch.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar