I've been working with the incredibly popular StarWars API and have successfully extracted data from the initial page of planets after some research. However, a new challenge has arisen.
My task now is to implement buttons that allow users to navigate through multiple pages of planet data, starting from the second page, and eventually looping back to the first page. Unfortunately, I'm struggling with this part as I am not sure how to dynamically update the URL based on user input.
One solution I considered was binding a variable to the URL that could be modified by the buttons' actions. I attempted to use the ++value
and --value
patterns to increment and decrement the variable accordingly, but it seems that these changes are not reflected in the URL for the subsequent fetch requests.
I must have made a mistake somewhere along the line, but I can't pinpoint where exactly. Your assistance in resolving this issue would be greatly appreciated.
Below is the code causing the problem:
value = 1
const prevButton = document.createElement("button");
prevButton.innerText = 'Prev Page'
prevButton.setAttribute("id", "prev-button")
document.body.append(prevButton);
prevButton.style.cssText = "background-color: violet; width: 150px; height: 45px; transform: translateY(-725%); margin-left: -10px;"
prevButton.addEventListener('click', () => {
return --value
})
const nextButton = document.createElement("button");
nextButton.innerText = 'Next Page'
nextButton.setAttribute("id", "next-button")
document.body.append(nextButton);
nextButton.style.cssText = "background-color: violet; width: 150px; height: 45px; transform: translateY(-825%); margin-left: 90.5%;"
nextButton.addEventListener('click', () => {
return ++value
})
const response = await fetch ('https://swapi.dev/api/planets/?page=' + value);
const planetsData = await response.json().then(planetsData => {
let results = planetsData.results;
results.forEach(planet => {
const wrapper = document.createElement("wrapper")
square.append(wrapper);
wrapper.style.cssText = 'background-color: red; width: 200px; height: 250px; margin: auto; margin-top: 1.5%; margin-left: 50px; display: flex; flex-wrap: nowrap; flex-direction: row;'
wrapper.innerHTML = '<div><h1>Name: ' + planet.name + '</h1>' +
'<h3><p>Climate: ' + planet.climate + '</p></h3>' +
'<p>Population: ' + planet.population +
'<p>Terrain: ' + planet.terrain + '</p></div>';
});
})