Elizabeth
Elizabeth

Reputation: 157

Increment JSON Data Array by One

enter image description hereI'm wondering why this i+=1 doesn't increment the array by 1. When I click on the button the entire array length is shown. Can someone advise me what I'm doing wrong. I'm trying to load JSON data from WP related to posts with a certain category. This category I'm loading (http://localhost:8888/wordpress/wp-json/wp/v2/photos?categories=12) has 2 posts total. When I console.log postsData.length, I get the value of 2. When I console log postsData I receive Object, Object Object, Object. These posts both load at the same time when the button is clicked, but I want the posts or each object to load 1 at a time. Below is the code:

var portfolioPostsBtn = document.getElementById("portfolio-posts-btn");
var portfolioPostsContainer = document.getElementById("portfolio-posts-container");

if (portfolioPostsBtn){
portfolioPostsBtn.addEventListener("click", function(){
      var ourRequest = new XMLHttpRequest();
      ourRequest.open('GET', 'http://localhost:8888/wordpress/wp-json/wp/v2/photos?categories=12');
      ourRequest.onload = function() {
        if (ourRequest.status >= 200 && ourRequest.status < 400) {
          var data = JSON.parse(ourRequest.responseText);
          //console.log(data);
          createHTML(data);

        } else {
          console.log("We connected to the server, but it returned an error.");
        }
      };

      ourRequest.onerror = function() {
        console.log("Connection error");
};

ourRequest.send();

});
}

function createHTML(postsData){
  var ourHTMLString = '';
// This for loop doesn't increment by 1
  for (var i=0; i<postsData.length; i += 1){
    console.log(postsData.length);
    ourHTMLString += '<h2>' + postsData[i].title.rendered + '</h2>';
    ourHTMLString += '<img class="gallery-test" src="' +postsData[i].acf.image + '"">'
  }
  portfolioPostsContainer.innerHTML = ourHTMLString;
}

Upvotes: 0

Views: 521

Answers (1)

user3366943
user3366943

Reputation: 263

let me try to understand your question correctly. if you're trying to just display one single post per click. here's what i think you may try:

let portfolioPostsBtn = document.getElementById("portfolio-posts-btn");
let portfolioPostsContainer = document.getElementById("portfolio-posts-container");

// keep the payload to avoid unnecessary data requests
let postsData = [];

// using this to track click history to display the next post
let counter = 0;

/** not needed for disabling the button **/
// cycle (postsData.length) one by one starting at index 0
// for ex, if there are 3 posts, it would do 0, 1, 2, 0, 1, 2, to eons
// const incrementCounter = () => {
// counter = (counter + 1)%(postsData.length)
// };

// create post html if there is postsData
postsData.length && createHTML();

if (portfolioPostsBtn && !postsData.length){
portfolioPostsBtn.addEventListener("click", function(){
      let ourRequest = new XMLHttpRequest();
      ourRequest.open('GET', 'http://localhost:8888/wordpress/wp-json/wp/v2/photos?categories=12');
      ourRequest.onload = function() {
        if (ourRequest.status >= 200 && ourRequest.status < 400) {
          let data = JSON.parse(ourRequest.responseText);
          //console.log(data);
          postsData = data;
          createHTML();

        } else {
          console.log("We connected to the server, but it returned an error.");
        }
      };

      ourRequest.onerror = function() {
        console.log("Connection error");
};

ourRequest.send();

});
}


function disableButton () {
  // this would only work if portfolio-posts-btn is an actual button,
  // otherwise, you'll need to disable the listener and show the
  // user the btn is disabled somehow
  portfolioPostsBtn.setAttribute('disable', true);
}

function createHTML() {
  const strTemplate = `
    <h2>${postsData[counter].title.rendered}</h2>
    <img class="gallery-test" src="${postsData[counter].acf.image}">`;
  // append to the added posts
  portfolioPostsContainer.innerHTML += strTemplate;
  counter++;
  postsData.length === counter && disableButton();
}

Upvotes: 1

Related Questions