Explore the Star Wars API using interactive buttons to navigate between different planetary pages

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>';
});
}) 

Answer №1

Here is an advanced example that expands upon my previous comment. While the buttons are hardcoded for simplicity, the main ideas highlighted are:

  1. Creating a separate function for the fetch process to be called whenever a button is clicked

  2. Utilizing the next and previous properties of the fetched data to determine which page should be shown next.

// Storing references to elements
const planets = document.querySelector('.planets');
const buttons = document.querySelector('.buttons');
const previous = document.querySelector('[data-id="previous"]');
const next = document.querySelector('[data-id="next"]');

// Adding event listener to the button container
buttons.addEventListener('click', handleClick);

// Defining base endpoint and initializing `data`
const base = 'https://swapi.dev/api/planets/?page=1';
let data = {};

// Fetching the first page
fetchData();

// Handling button clicks to fetch the next page based on the clicked button
function handleClick(e) {
  if (e.target.matches('.button')) {
    const { id } = e.target.dataset;
    fetchData(id);
  }
}

// Fetching data based on the provided id, or defaulting to the base endpoint
// Creating HTML from fetched data and updating button states accordingly
async function fetchData(id) {
  const endpoint = data[id] || base;
  const res = await fetch(endpoint);
  data = await res.json();
  const html = createHTML(data.results);
  planets.innerHTML = html;
  previous.disabled = !data.previous ? true : false;
  next.disabled = !data.next ? true : false;
}

// Generating HTML content from the fetched data array using map
function createHTML(data) {
  return data
    .map(planet => {
      return `
        <section class="planet">
          <h4>${planet.name}</h4>
          <p>Population: ${planet.population}</p>
          <p>Terrain: ${planet.terrain}</p>
        </section>
      `;
    })
    .join('');
}
.planet { border: 1px solid #efefef; padding: 0.4em; }
.button:hover { cursor: pointer; }
<section class="buttons">
  <button data-id="previous" class="button">Prev</button>
  <button data-id="next" class="button">Next</button>
</section>
<section class="planets"></section>

Additional Resources

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Add a JavaScript library to the header directly from the body of a webpage, ensuring it is exclusive to a single

I am using the Google Charts JS library on a single page within my project, with external and global headers and footers. The head tags are located in a head.php file, where all required JS libraries are included. The structure of my pages is as follows: ...

Implementing a PHP button update functionality sans utilizing an HTML form

I need a way to update my database with just a click of a button, without using any forms or POST requests. Most examples I've seen involve updating through forms and the $_POST method. Is there a simpler way to update the database by directly click ...

Choose an input field using jQuery that is specified by its name

I am currently using jquery form validator to validate all the fields within my form. Within the form validator, I have implemented the following code snippet to determine if an input field is labeled with the name minExperience. errorPlacement: function ...

java code unicode feature in csharp

Here's the code I am using: $(document).ready(function () { var breadCrumps = $('.breadcrumb'); breadCrumps.find('span').text("<%= ArticleSectionData.title %>"); }); The 'title' property contains values en ...

WSO2 PayloadFactory is delivering JSON data neatly packaged in a JSONObject

Currently, I am utilizing WSO2 API Manager 1.7.0 and experimenting with a simple payloadfactory to switch a call from a GET to a POST while passing in a json payload. In analyzing the log files, it seems that WSO2 is sending the json enveloped within {"js ...

Design a custom favicon for a website link associated with JavaScript

On my website, I have a JavaScript link that users can choose to drag to their browser's link bar. However, since there is no associated site with a Favicon, the link always appears with a blank icon. Is there a way to associate a Favicon with it at t ...

Chrome mistakenly identifying octet-stream as a .png image

My application incorporates the use of Google Maps API V3 and ASP.Net, utilizing OverlayView to customize icons on the map. The icon's image is configured within the onAdd event by dynamically adjusting the background CSS property using JavaScript. T ...

I am interested in tallying up the number of adjacent matching elements within an array and then providing the final count

I have an array and want to find all neighboring matches, count them, and then return the count. This needs to be done in a loop using .map() so that I don't need to store memory of what was counted beyond the current element. The number of current el ...

Shifting a div from side to side

I don't have much experience with coding, so I was hoping for some assistance. My goal was to create a div that moves back and forth using toggleClass; $('div').on('click', function() { $(this).toggleClass('active') ...

What is the best way to send only one variable from a complex JavaScript file?

index.js $(window).resize(function(){ var page = location.pathname.split('/').slice(-1)[0]; if (page != "minw.php") {goback = location.pathname;} var w1 = document.documentElement.clientWidth; var minw = 800; if (w1 < minw ...

Detecting onClick event upon form submission

My form collects data to initiate either an external process (bash script) or a database query (using queryBuilder). To provide feedback to the user and prevent multiple submissions, I want to update the submit button with a message like 'Processing.. ...

The done() method in AJAX is triggered upon completion of all request processing tasks

After making an AJAX request to delete data from a list, I follow up with another AJAX request to update the list with new data. Here is the code for deleting data: $.ajax({ method: "DELETE", url: urlRequest, headers: { 'X-CSRF-TO ...

Discovering the content of an internal Database or Table in TYPO3 and showcasing it using JavaScript, JQuery, or AJAX

As a newcomer to TYPO3, I must admit that it's quite intricate, but I'm making progress. All I'm looking for is a simple method to extract content from an internal TYPO3 Database Table that I've set up and send it over to JavaScript/JQ ...

Keep running AJAX operations using setTimeout even when the browser window has been closed

I have set up a PHP page that sends an AJAX request to another PHP page containing a casperJS script, which is triggered by a button click and runs every 60 seconds. My goal is to be able to close the browser window while still allowing the AJAX requests ...

Guide on linking JavaScript files in Node.js

I am having trouble getting my javascript to work properly. My javascript files are located in the public/javascripts directory. app.js app.use(express.static(path.join(__dirname, 'public'))); views/layout.pug doctype html html head ti ...

JavaScript does not allow the use of variables outside of functions

As someone diving into the world of Javascript after working extensively with server-side languages like PHP, I've noticed a peculiar issue. It seems that I am unable to access variables defined outside of a function from within the function itself. T ...

Regular expressions for identifying operands and operators in a calculator application implemented with JavaScript

I am currently working on a JavaScript project to create a basic calculator. I am in need of a way to validate each item in an array of operands (sequences of digits) and operators (+, -, *, /, ** for power). I have managed to create regex patterns for di ...

Encountering issues with the JsonObjectRequest implementation within my project

When attempting to retrieve JSON data from a URL, an issue arises when running the application. Error:(34, 83) error: incompatible types: int cannot be converted to String Error:Execution failed for task ':app:compileDebugJavaWithJavac'. The ...

A method of iteration that allows us to traverse through an object, regardless of whether it contains a single item or an array of items, is known as dynamic looping

I am dealing with a JSON output that can have different types of data: There may be an array of objects like this: var data = { "EARNINGS": [ { "PAYMENT": "1923.08", ...

Converting from C# to JavaScript results in JSON decoding failing to capture a specific property

I am facing an issue with a c# object that I need to send to my JavaScript code. Although I can iterate over the items in the list, I am unable to access the string property ('Period'). When referencing the object in JS, no property is shown at ...