I make requests to the PokeApi and I can retrieve the data just fine through axios, it returns an object with the following structure:
{
name:"bulbasaur"
url:"https://pokeapi.co/api/v2/pokemon/1/"
name:"ivysaur"
url:"https://pokeapi.co/api/v2/pokemon/2/"
name:"venusaur"
url:"https://pokeapi.co/api/v2/pokemon/3/"
}
Everything is going fine up to this point, but then I make a request to the address that comes in the "url" property and it returns an object with data, among them:
{
"base_experience": 101,
"forms": [
{
"name": "ditto",
"url": "https://pokeapi.co/api/v2/pokemon-form/132/"
}
],
"height": 3,
"sprites": {
"back_default": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/back/132.png",
"back_female": null,
"back_shiny": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/back/shiny/132.png",
"back_shiny_female": null,
"front_default": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/132.png",
"front_female": null,
"front_shiny": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/shiny/132.png",
"front_shiny_female": null
}
}
The request is made but, when I want to show it in any of the photos in an image tag, it marks the sprites property as undefined.
This is the component code:
import React, { useState, useEffect } from "react";
import axios from "axios";
export default function Pokemon(props) {
const pokemonInfo = props.pokemonInfo;
let imagenes = {};
const [pokemon, setPokemon] = useState([]);
const getPokemonInfo = async url => {
const req = await axios.get(url);
const pokeInfo = await req.data;
console.log(`data ${JSON.stringify(pokeInfo.sprites)} END`);
imagenes = pokeInfo.sprites;
console.log(`imagenes ${imagenes.back_default}`);
setPokemon(pokeInfo);
};
useEffect(() => {
getPokemonInfo(pokemonInfo.url);
}, []);
return (
<>
<li>
<h1>{pokemon.name}</h1>
<img src={imagenes.back_default} />
<p>weight {pokemon.weight}</p>
</li>
</>
);
}
I also attach the url of the PokedexConReact project for a better understanding.
1.- Why don't you convert your images into a state, Example:
2.- Then you can update that example state:
3.- You would already be able to show the image as you are showing it.
4.- Try it and tell me what happened.