I am learning react.
I have a simple react app sample that :
- Fetch users
- Once users are fetched, show their name on a Card
What I'd like to do is to expand this sample. Instead of using a simple list of users, I'd like to use a list of pokemons. What I try to do is :
- Fetch the list of pokemon and add in
state.pokemons
- Show the Card with the pokemon name from
state.pokemons
- From that list, get the
URL
to fetch the detail of the given pokemon and add instate.pokemonsDetails
- From the
state.pokemonsDetails
, update the Cards list to show the image of the pokemon.
My problem is: I don't even know how to re-render the Cards list after a second fetch.
My question is: How to update the Cards list after the second fetch?
See my code below:
import React from "react";
import CardList from "../components/CardList";
import SearchBox from "../components/SearchBox"
import Scroll from "../components/Scroll"
import './App.css';
class App extends React.Component{
constructor(){
super();
this.state = {
pokemons:[],
pokemonsDetails:[],
searchfield: ''
}
}
getPokemons = async function(){
const response = await fetch('https://pokeapi.co/api/v2/pokemon/?offset=0&limit=20');
const data = await response.json();
this.setState({pokemons:data.results})
}
getPokemonDetails = async function(url){
//fetch function returns a Promise
const response = await fetch(url);
const data = await response.json();
//console.log('getPokemonDetails', data);
this.setState({pokemonsDetails:data});
}
componentDidMount(){
this.getPokemons();
}
onSearchChange = (event) => {
this.setState({searchfield: event.target.value})
}
render(){
const {pokemons, pokemonsDetails, searchfield} = this.state;
if(pokemons.length === 0){
console.log('Loading...');
return <h1>Loading....</h1>
}else if (pokemonsDetails.length === 0){
console.log('Loading details...');
pokemons.map(pokemon => {
return this.getPokemonDetails(pokemon.url);
});
return <h1>Loading details....</h1>
}else{
return(
<div>
<h1>Pokedex</h1>
<SearchBox searchChange={this.onSearchChange}/>
<Scroll>
<CardList pokemons={pokemons}/>
</Scroll>
</div>
);
}
}
}
export default App;
Some remarks :
- I can see a problem where my Cards list is first created with
state.pokemons
, then, I would need to update Cards list withstate.pokemonsDetails
. The array is not the same. - Second problem, I don't even know how to call the render function after
state.pokemonsDetails
is filled with the fetch. I set the state, but it looks like render is not called every time - More a question than a remark. The way I update my state in
getPokemonDetails
might be incorrect. I keep only one detail for one given pokemon. How to keep a list of details? Should I use something else thansetState
to expandpokemonsDetails
array?