Home > Software engineering >  Fetch and display API information using Javascript
Fetch and display API information using Javascript

Time:01-23

fetch("https://wptavern.com/wp-json/wp/v2/posts")
  .then((response) => {
    if (response.ok) {
      return response.json();
    } else {
      throw new Error("NETWORK RESPONSE ERROR");
    }
  })
  .then((data) => {
    console.log(data);
    displayDetails(data);
  })
  .catch((error) => console.error("FETCH ERROR:", error));

//*function displayDetails(data) {
  const informations = data[0]; //create a variable and store the array you need to access
  const informationsDiv = document.getElementById("informations"); //create a vaiable with a div to display the data

  const informationsTitle = informations.title.rendered; //create a variable and access the specific data, title in this case
  const heading = document.createElement("h1"); //create a heading variable h1
  heading.innerHTML = informationsTitle;
  informationsDiv.appendChild(heading);

  const informationsImage = document.createElement("img"); //create a variable for the image
  informationsImage.src = informations.episode_featured_image; //specify the image source inside the array
  informationsDiv.appendChild(informationsImage);

  const informationsDate = informations.date; //create a variable and access the date
  const heading1 = document.createElement("p"); //create a variable to use in the DOM
  heading1.innerHTML = informationsDate;
  informationsDiv.appendChild(heading1); //append the data
//}

function displayDetails(data) {
  let informationsDiv = document.getElementById("informations");
  for(var i = 0; i < data.length; i  ) {
      let informations = data[i];
      let informationsTitle = informations.title.rendered;
      let heading = document.createElement("h1");
      heading.innerHTML = informationsTitle;
      informationsDiv.appendChild(heading);
      let informationsImage = document.createElement("img");
      informationsImage.src = informations.episode_featured_image;
      informationsDiv.appendChild(informationsImage);
      let informationsDate = informations.date;
      let heading1 = document.createElement("p");
      heading1.innerHTML = informationsDate;
      informationsDiv.appendChild(heading1);
  }
}
.swiper {
    margin: auto;
    padding: auto;
        width:100%;
        height: 100%;
  }

.swiper-slide {
    text-align: center;
    font-size-adjust: 15px;
    background: #fff;
/* Center slide text vertically */
    display: -webkit-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
    -webkit-box-pack: center;
    -ms-flex-pack: center;
    -webkit-justify-content: center;
    justify-content: center;
    -webkit-box-align: center;
    -ms-flex-align: center;
    -webkit-align-items: center;
    align-items: center;
    background-color: #c2bdd1;
}

.swiper-slide img {
    display: block;
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
html,body {
    
    height:100%;
    background: #eee;
    font-family: Helvetica Neue, Helvetica, Arial, sans-serif;
    font-size: 14px;
    color: #000;
    margin: auto;
    padding: 0;
}

#informations{
    max-width: 700px;
    text-align: center;
    padding: 30px 30px 12px 30px;
    color: rgb(252, 252, 252);
    background-color: #7766d7;
    border: 4px solid #9387f2;
    border-radius: 5px;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper@8/swiper-bundle.min.css" />
  <link rel="stylesheet" href="style.css" />

  <!--Script-->
  <script src="script/script.js"></script>
  <!-- Swiper -->
  <div >
    <div >
      <div >
        <div id="informations"></div>
      </div>
      <div >Slide 2</div>
      <div >Slide 3</div>
      <div >Slide 4</div>
      <div >Slide 5</div>
      <div >Slide 6</div>
      <div >Slide 7</div>
      <div >Slide 8</div>
      <div >Slide 9</div>
    </div>
    <div ></div>
    <div ></div>
  </div>
  <!-- Swiper JS -->
  <script src="https://cdn.jsdelivr.net/npm/swiper/swiper-bundle.min.js"></script>

  <!-- Initialize Swiper -->
  <script>
    var swiper = new Swiper(".mySwiper", {
      allowTouchMove: true,
      navigation: {
        nextEl: ".swiper-button-next",
        prevEl: ".swiper-button-prev",
      },
      keyboard: {
        enabled: true,
      }

    });
  </script>
</body>

</html>

I am building a carousel where on every page I want to display information (title, image, date) taken from this API: https://wptavern.com/wp-json/wp/v2/posts

So far I managed to write this script:

fetch("https://wptavern.com/wp-json/wp/v2/posts")
  .then((response) => {
    if (response.ok) {
      return response.json();
    } else {
      throw new Error("NETWORK RESPONSE ERROR");
    }
  }).then((data) => {
    console.log(data);
    displayDetails(data);
  }).catch((error) => console.error("FETCH ERROR:", error));

function displayDetails(data) {
  const informations = data[0];
  const informationsDiv = document.getElementById("informations");
  const informationsTitle = informations.title.rendered;
  const heading = document.createElement("h1");
  heading.innerHTML = informationsTitle;
  informationsDiv.appendChild(heading);
  const informationsImage = document.createElement("img");
  informationsImage.src = informations.episode_featured_image;
  informationsDiv.appendChild(informationsImage);
  const informationsDate = informations.date;
  const heading1 = document.createElement("p");
  heading1.innerHTML = informationsDate;
  informationsDiv.appendChild(heading1);
}

The problem is, this works only on the first slide. If I try to call the same function for slide n2 and change all the variables and the start of the array, from data[0] to data[1], then slide n1 doesn't showcase info anymore, but slide n2 does!

I also added a picture of HTM because I don't know how to format code properly and stack overflow is not allowing me to post the question.

The end result should display all the recent articles provided by the API.

Thank you for your time.

CodePudding user response:

I've updated your code, this should work:

fetch("https://wptavern.com/wp-json/wp/v2/posts")
    .then((response) => {
      if (response.ok) {
        return response.json();
      } else {
        throw new Error("NETWORK RESPONSE ERROR");
      }
    })
    .then((data) => {
      console.log(data);
      displayDetails(data);
    })
    .catch((error) => console.error("FETCH ERROR:", error));


  function displayDetails(data) {
    let informationsDiv = document.getElementById("slider");
    for(var i = 0; i < data.length; i  ) {
      var slide = document.createElement("div");
      slide.className = "swiper-slide";
      var slideContent = document.createElement("div");
      slideContent.className = "informations";
      let informations = data[i];
      let informationsTitle = informations.title.rendered;
      let heading = document.createElement("h1");
      heading.innerHTML = informationsTitle;
      slideContent.appendChild(heading);
      let informationsImage = document.createElement("img");
      informationsImage.src = informations.episode_featured_image;
      slideContent.appendChild(informationsImage);
      let informationsDate = informations.date;
      let heading1 = document.createElement("p");
      heading1.innerHTML = informationsDate;
      slideContent.appendChild(heading1);
      slide.appendChild(slideContent);
      informationsDiv.appendChild(slide);
    }
  }
.swiper {
    margin: auto;
    padding: auto;
        width:100%;
        height: 100%;
  }

.swiper-slide {
    text-align: center;
    font-size-adjust: 15px;
    background: #fff;
/* Center slide text vertically */
    display: -webkit-box;
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;
    -webkit-box-pack: center;
    -ms-flex-pack: center;
    -webkit-justify-content: center;
    justify-content: center;
    -webkit-box-align: center;
    -ms-flex-align: center;
    -webkit-align-items: center;
    align-items: center;
    background-color: #c2bdd1;
}

.swiper-slide img {
    display: block;
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
html,body {
    
    height:100%;
    background: #eee;
    font-family: Helvetica Neue, Helvetica, Arial, sans-serif;
    font-size: 14px;
    color: #000;
    margin: auto;
    padding: 0;
}

.informations{
    max-width: 700px;
    text-align: center;
    padding: 30px 30px 12px 30px;
    color: rgb(252, 252, 252);
    background-color: #7766d7;
    border: 4px solid #9387f2;
    border-radius: 5px;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swiper@8/swiper-bundle.min.css" />
  <link rel="stylesheet" href="style.css" />

  <!--Script-->
  <script src="script/script.js"></script>
  <!-- Swiper -->
  <div >
    <div  id="slider">
    </div>
    <div ></div>
    <div ></div>
  </div>
  <!-- Swiper JS -->
  <script src="https://cdn.jsdelivr.net/npm/swiper/swiper-bundle.min.js"></script>

  <!-- Initialize Swiper -->
  <script>
    var swiper = new Swiper(".mySwiper", {
      allowTouchMove: true,
      navigation: {
        nextEl: ".swiper-button-next",
        prevEl: ".swiper-button-prev",
      },
      keyboard: {
        enabled: true,
      }

    });
  </script>
</body>
</html>

It basically creates a new swiper-slide for each result of the API, and appends it to your slider.

  • Related