How to access key pair values of individual elements in an array multiple times in 1 API call?

The API request that I am using will return an array of elements and within each element, there are multiple key pair values.

A similar response would like this API: https://www.poemist.com/api/v1/randompoems, which returns an array of poems.

[
 {
  "title": "...."
  "content": "..."
  "url" : "..."
 }
 {
  "title": "...."
  "content": "..."
  "url" : "..."
 }
 {
  "title": "...."
  "content": "..."
  "url" : "..."
 }
]

I am using Webflow's embedded code feature to display the responses from the API in multiple boxes:

Example of how data is displayed

An example snippet:

<h1 id ="title"></h1>
<p id ="content"></p>
<script>
    fetch("https://www.poemist.com/api/v1/randompoems")
      .then((res) => res.json())
      .then((data) => {
        const { title, content} = data[0];
        document.getElementById("title").textContent = title
        document.getElementById("content").textContent = content
      });
</script>

My limits:

In the boxes, there are other unique div classes that contain unique info. So I don't think I can use a for loop.

My question:

I could use the exact same snippet 4 times and change the element respectively, but I will be making 4 API calls. Is there a way that I could call the API just once and then access the data individually? Webflow allows you to add a script at the head tag, so the API request do not necessarily need to be inside the individual embedded code snippet.

1 answer

  • answered 2020-06-03 01:56 Wb16

    <h1 id ="title_0"></h1>
    <p id ="content_0"></p>
    <script>
        fetch("https://www.poemist.com/api/v1/randompoems")
          .then((res) => res.json())
          .then((data) => {
            for (i=0; i<=4; i++){
            const {title, content} = data[i];
            document.getElementById("title_" + i).textContent = title
            document.getElementById("content_" + i).textContent = content
            }
          });
    </script>