I´m studying Javascript. And for that I am making a Pokémon Game based on the PokéAPI
To make it simple, I want to retrieve - filter - Pokémons with types Fire, Water & Grass.
I understand I should go to data > types > (look in the slots 1 & 2) > search for grass, fire & water.
So this is my code, so far, and I was thinking if I could do it BEFORE retrieving the data to the API. Otherwise I´ll have to retrieve EVERY Pokémon and then filter them.
const baseUrl = 'https://pokeapi.co/api/v2/pokemon/?limit=150'
try {
fetch(baseUrl)
.then(response => {
const responseJson = response.json()
return responseJson
})
.then(async data => {
const pokemons = data.results
for (const pokemon of pokemons) {
pokemon.data = await fetch(pokemon.url).then(res => res.json())
}
console.log(pokemons)
})
.catch(error => {
console.error(error)
})
} catch (error) {
console.error(error)
}
CodePudding user response:
Of course, you can't filter with data that you haven't yet, but you can save the data in localStorage
for the first time and use it next times. You can see examples here
CodePudding user response:
If you do not normalize the API data you have to filter using this list. But when you get the pokemon list you can normalize the list to a more friendly structure to your app.
function normalizeList (item = {}) {
const { name, data } = item
// Define your normalized data here
return {
name,
types: data.types
}
}
If you need to transform/parse or whatever I recomend you to create a PokemonModel and create Pokemon Class instances:
class PokemonModel {
constructor(data = {}) {
this.name = data.name
this.types = this._getTypes(data.types)
}
_getTypes(types = []) {
return types.map((type) => {
return {
name: type.name
}
})
}
}
Your code with PokemonModel:
class PokemonModel {
constructor(data = {}) {
this.name = data.name
this.types = this._getTypes(data.types)
}
_getTypes(types = []) {
return types.map((type) => {
return {
name: type.name
}
})
}
}
const baseUrl = 'https://pokeapi.co/api/v2/pokemon/?limit=150'
const pokemonList = []
try {
fetch(baseUrl)
.then(response => {
const responseJson = response.json()
return responseJson
})
.then(async data => {
const pokemons = data.results
for (const pokemon of pokemons) {
pokemon.data = await fetch(pokemon.url).then(res => res.json())
pokemonList.push(new PokemonModel(pokemon.data))
}
console.log(pokemonList)
})
.catch(error => {
console.error(error)
})
} catch (error) {
console.error(error)
}