I am using the Star Wars API (SWAPI) for a project. I am in the process of learning fetch API. An issue I have is that, I have a section for species and when I press the button it returns certain attributes for that species. This is the code:
function getSpecies() {
let numberSpecies = Math.floor((Math.random()*37)+1)
let apiUrl = 'https://swapi.dev/api/species/' + numberSpecies
fetch(apiUrl)
.then(function(response){
return response.json()
})
.then (function(json){
console.log(json)
let name = document.getElementById('species-name')
let classification = document.getElementById('classification')
let designation = document.getElementById('designation')
let language = document.getElementById('language')
let lifespan = document.getElementById('lifespan')
name.innerText = `Species Name: ${json['name']}`;
classification.innerText = `Classification: ${json['classification']}`;
designation.innerText = `Designation: ${json['designation']}`;
language.innerText = `Language: ${json['language']}`;
lifespan.innerText = `Lifespan: ${json['average_lifespan']}-years`;
})
})
}
So, when I press the button it fetches the info I want. However, there is a data attribute in the species section which is labelled 'people' and this show the people that belong to that species. The 'people' attribute is another link within the SWAPI. In other words, the attribute is made up of more urls which require using fetch.
Mu problem is I want to call those multiple urls and return the 'name' from them and then show it. So, if the species is 'Human' it has four people and therefore 4-url's and I want to fetch all those url's and only grab the 'name' of each 'Human'. This is what I have tried (it goes directly below the last line of code i.e below lifespan.innertext):
const peopleUrl = json.people
peopleUrl.forEach(people = (data) => {
fetch(data)
.then(function(response){
return response.json()
})
.then (function(json){
console.log(json)
let inhabitants = document.getElementById('inhabitants')
inhabitants.innerText = json.name
})
})
This however, only return the name of the last person in the array and not all of them. Is there a way I can fetch all the 'names'?