I want to do the following: get a random name with fetch from this website https://swapi.dev/api/people/, which I did and I can see it in my html page then I want also to get a random planet, here I need to access the homeworld key, and to return the link, before returning the link I formatted to get a random URL and from this one I also have to show the name of the planet on my page. The first fetch works fine, at least I think but the third .then() is not working or at least I don't know how to access the information from the homeworld URL. This is my first time trying fetch() and it will be nice if you can help me telling where I did wrong in code and maybe different solutions but not so complicated.
let randomNumber = Math.floor(Math.random()*9)
const fetchPromise = fetch("https://swapi.dev/api/people/");
let test
let test2
let planets = document.querySelector('#age')
fetchPromise
.then((response) => {
if (!response.ok) {
throw new Error(`Http error: ${response.status}`);
}
return response.json();
})
.then((json) => {
console.log(json.results[randomNumber].name)
showRandomUserData(json)
test = json.results[0].homeworld
test = test.slice(0, -2)
// console.log(test + randomNumber + "/");
// console.log(test + "/" + randomNumber + "/");
test = test + randomNumber + "/";
return fetch(test)
// return fetch("https://swapi.dev/api/planets/2/");
})
.then(response => response.json()).then(json =>
{ test2=json.name
console.log(test2);
planets.innerHTML = test2
})
showRandomUserData = (randomUser) => {
document.querySelector("#name").innerHTML =
randomUser.results[randomNumber].name;
}
Solved
return fetch(test), instead ofreturn test, and then.then(response => response.json()).then(json => { console.log(json.name) })