How can I solve Type Error: completedata.map is not a function while trying to display the data in a card on a webpage

Viewed 24

This is my JavaScript code whereby am fetching data from an externa API which am trying to display it on a webpage using a card.

<script>
  fetch(
    "https://api.airtable.com/v0/appBTaX8XIvvr6zEC/tblYPd5g5k5IKIc98?api_key=##"
  ).then((data) => {
    // console.log(data)
    return data.json();
  }).then((completedata) => {
    //console.log(completedata.records[2])
    let data1 = "";
    completedata.map((values) => {
      data1 = `
        <div class="card">
            <img src=${values.avatar} alt="Avatar" class="avatar">
            <p class="name">${values.Name}</p>
            <p class="occupation">${values.occupation}</p>
        </div>
      `;
    });
    document.getElementById("card").innerHTML = data1;
  }).catch((error) => {
    console.log(error);
  });
</script>
1 Answers

As per clarifications in comments:

console.log(completedata) gives me : {records: Array(83)}

So you need to apply .map function on the array you got, which is completedata.records in your current case.

And next issue you had is data1 = inside the map function. On each iteration you are reassigning data1 to the new string ignoring all the previous iterations. You can achieve what you want by mapping your array of object to array of html strings and applying .join on this result array, which will produce the single html string.

fetch(
  "https://api.airtable.com/v0/appBTaX8XIvvr6zEC/tblYPd5g5k5IKIc98?api_key=##"
)
  .then((data) => data.json())
  .then((completedata) => {
    const html = completedata.records
      .map((values) => {
        return ` 
          <div class="card">
            <img src=${values.avatar} alt="Avatar" class="avatar">
            <p class="name">${values.Name}</p>
            <p class="occupation">${values.occupation}</p>
          </div>
        `;
      })
      .join("");
    document.getElementById("card").innerHTML = html;
  })
  .catch((error) => {
    console.log(error);
  });
Related