-2

I need help by editing my code on how i can be able to display the data i have fetched from an external api and that from a local json file so that my card can show the user's avatar,name,occcupation,total number of impressions and total number of conversions on the same card.

Here is my code:

<script>
        
        fetch("https://api.airtable.com/v0/appBTaX8XIvvr6zEC/tblYPd5g5k5IKIc98?api_key=key4v56MUqVr9sNJv")
      
            .then((data)=>{
               // console.log(data)
               return data.json();

            })
            .then ((completedata)=>{
             //console.log(completedata.records[0])
             //an empty variable to catch the incoming data
             let data1="";
             // Then i added a html template to the data1 variable
               completedata.records.forEach((values)=>{
                data1+=` 
                <div class="card">
                    <span class="avatarLetter">${values.fields.Name.substr(0,1)}</span>
                    <p class="name">${values.fields.Name}</p>
                    <p class="occupation">${values.fields.occupation}</p>
             </div> `;
               });

               document.querySelector("#card").innerHTML=data1;
            })

            
            .catch((error)=>{
             console.log(error);

            })
    //pulling data from local json file
    fetch('./logs.json')
  .then((response) => {
    return response.json();
  })
  .then((data) => {
    // console.log(data);
    let data1 = "";
  let totalImpressions = 0;
  let totalConversions = 0;
    data.forEach((values) => {
      totalImpressions += values.impression;
      totalConversions += values.conversion;
      data1 += ` 
            <div class="card">
            <p class="impression">${values.impression}</p>
            <p class="conversion">${values.conversion}</p>
            </div> `;
    });
    data1 += `<div>Total impressions = ${totalImpressions} Total conversions = ${totalConversions}</div>`;
    document.querySelector("#card").innerHTML = data1;

  })
  .catch((error) => {
    console.log(error);
  })

        </script>

1 Answers1

0

When you write second time

document.querySelector("#card").innerHTML = data1;

you overwrite #card content.

The right way:

document.querySelector("#card").innerHTML += data1;
  • While correct in the sense that this snippet resolves the OP’s identified issue, I wouldn’t call this “the right way” as the solution you propose is not a particularly performant one in all browsers; see https://stackoverflow.com/questions/11515383/why-is-element-innerhtml-bad-code – esqew Sep 09 '22 at 20:08
  • kindly show it by editing my code – Rick Derick Sep 09 '22 at 20:36