So far, we used the heroโs name to fetch the image, description, and the heroโs abilities. This approach works for Axe, but it doesnโt work for some heroes.
One example is Shadow Fiend.
Shadow Fiend is also called Nevermore. You can see both Shadow Fiend and Nevermore in the response from the heroes endpoint.
The lores endpoint and the hero_abilities use nevermore instead of shadow_fiend. This tells us we canโt use Shadow Fiend in the API. We need to use Nevermore.
But if we use nevermore, we donโt get the Heroโs imageโฆ
Why? Because we checked the heroes endpoint for Shadow Fiend! (localized_name contains Shadow Fiend).
To get the image, we need to check against Nevermore instead.
Robustness for Hero Image
Nevermore is located in the heroโs name attribute.
To get nevermore, we can get the heroโs name property and remove the npc_dota_hero_ part. We can remove it by replacing that part with an empty string.
zlFetch(`${dotaApi}/constants/heroes`) .then(response => { const heroes = Object.values(response.body).map(hero => { const name = hero.name.replace('npc_dota_hero_', '') console.log(name) })
Weโll put this value into the formatted data. Weโll call this npcHeroName to make things clear.
zlFetch(`${dotaApi}/constants/heroes`) .then(response => { const heroes = Object.values(response.body).map(hero => { return { name: hero.localized_name, npcHeroName: hero.name.replace('npc_dota_hero_', ''), attackType: hero.attack_type.toLowerCase(), primaryAttribute: hero.primary_attr, roles: hero.roles.map(role => role.toLowerCase()), image: `https://api.opendota.com${hero.img}` } // ... })We can now find nevermore from the list of heroes.
zlFetch(`${dotaApi}/constants/heroes`) .then(response => { const heroes = Object.values(response.body).map(hero => { return { name: hero.localized_name, npcHeroName: hero.name.replace('npc_dota_hero_', ''), attackType: hero.attack_type.toLowerCase(), primaryAttribute: hero.primary_attr, roles: hero.roles.map(role => role.toLowerCase()), image: `https://api.opendota.com${hero.img}` } }) const hero = heroes.find(h => h.npcHeroName() === heroName) heroImageEl.src = `${hero.image}` }
But the heroโs name is not Nevermore. It is Shadow Fiend. We need to insert Shadow Fiend into the DOM instead. We can do this by setting the textContent after we found the hero.
zlFetch(`${dotaApi}/constants/heroes`) .then(response => { const heroes = Object.values(response.body).map(/* ... */) const hero = heroes.find(h => h.npcHeroName === heroName) // Set the hero's name heroNameEl.textContent = hero.name heroImageEl.src = `${hero.image}` }) .catch(console.log)At this point, we can remove the capitalize function since we no longer use it.
Welcome! Unfortunately, you donโt have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson