skip to Main Content

I have some code that displays an array from a json object based on the id.

I’d like to write a function that allow users to click a button see the next item (id 1), then the one after (id 2), etc. What approach should I take?

JSON:

[
  {
    "id": 0,
    "last_name": "Dan",
    "first_name": "Terry"
  },
  {
    "id": 1,
    "last_name": "Cal",
    "first_name": "Adam"
  },
  {
    "id": 2,
    "year": 2015,
    "last_name": "Brooke",
    "first_name": "Lily"
  }
 ]

JS:

fetch('data.json')
  .then(function (response) {
    return response.json();
  })
  .then(function (data) {
    appendData(data);
  })
  .catch(function (err) {
    console.log(err);
  });


function appendData(data) {
    var mainContainer = document.getElementById("myData");
    var taser
    
    for (var i = 0; i < data.length; i++) {
      if (data[i].id === 0) {      

      var div = document.createElement("div");
      div.innerHTML = data[i].first_name + data[i].last_name;
      mainContainer.appendChild(div);
    }
  }
}

HTML:

<body>
  <div id="myData"></div>

<button id="btn">next</button>
</body>

2

Answers


  1. I think your looking for something like this.

    // fetch('data.json')
    //   .then(function (response) {
    //     return response.json();
    //   })
    //   .then(function (data) {
    //     appendData(data);
    //   })
    //   .catch(function (err) {
    //     console.log(err);
    //   });
    let json = [
      {
        "id": 0,
        "last_name": "Dan",
        "first_name": "Terry"
      },
      {
        "id": 1,
        "last_name": "Cal",
        "first_name": "Adam"
      },
      {
        "id": 2,
        "year": 2015,
        "last_name": "Brooke",
        "first_name": "Lily"
      }
    ];
    let mainContainer = document.getElementById("myData");
    let div = document.createElement("div");
    let counter = 0
    div.innerText = json[0].first_name + ' ' + json[0].last_name
    mainContainer.appendChild(div);
    function appendData() {
      counter++;
      for (let i = 0; i < json.length; i++) {
        if (json[i].id === counter) {
          div.innerText = json[i].first_name +' ' + json[i].last_name;
        }
      }
    }
    <div id="myData"></div>
    
    <button onclick="appendData()" id="btn">next</button>
    Login or Signup to reply.
    • Fetch the data using async / await
    • add the next button event "click" listener using addEventListener() to increment and loop the currentUser index to get the user data from:
    <div id="user"></div>
    <button id="next" type="button">next</button>
    
    const el = (sel, par) => (par || document).querySelector(sel);
    const elNew = (tag, prop) => Object.assign(document.createElement(tag), prop);
    
    const elUser = document.querySelector("#user");
    const elNext = document.querySelector("#next");
    
    const showUser = (user) => {
        const elDiv = elNew("div", {
            className: "item-user",
            textContent: `${user.first_name} ${user.last_name}`
        });
        elUser.innerHTML = ""; // Clear existing
        elUser.append(elDiv);
    };
    
    (async() => {
        try {
            let currentUser = 0;
    
            const res = await fetch('data.json');
            const data = await res.json();
    
            showUser(data[currentUser]); // Show first one
    
            elNext.addEventListener("click", () => {
                currentUser += 1; // Advance
                currentUser %= data.length; // Loop-back to index 0
                showUser(data[currentUser]); // Show next
            });
        } catch (err) {
            console.error(err);
        }
    })();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search