0

I'm developing a simple ES6 API call using fetch, trying to do it without any library.

When I'm setting the results in HTML, I'm using a forEach function to iterate the array, but it overrides itself.

The code entire code:

 results.forEach(result =>{
ulResults.innerHTML = `
<section class="${result.lighthouseResult.configSettings.emulatedFormFactor}-strategy">
Your website overall ${result.lighthouseResult.configSettings.emulatedFormFactor} performance is ${result.loadingExperience.overall_category}.
</section>
`

The entire js code:

// var STRATEGIES = ['desktop', 'mobile'];
const urlInput = document.getElementById('urlInput')
const strategySelector = document.getElementById('strategySelector');
const mobileStrategy = document.getElementById('mobile');
const desktopStrategy = document.getElementById('desktop');
const themeSwitcher = document.getElementById('theme-switcher');
const loader = document.getElementById('loader');
const ulResults = document.getElementById('results');

let baseApiUrl = 'https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url='
let apiKey = 'AIzaSyBRPIT29qvlQ3p7pxuw9XFZVqnzRc-xmII';
let url = '';
let strategy = [];
let results = [];

mobileStrategy.addEventListener('click', ()=>{
  if(mobileStrategy.checked){
    strategy.push('mobile')
  }
})

desktopStrategy.addEventListener('click', ()=>{
  if(desktopStrategy.checked){
    strategy.push('desktop')
  }
})
themeSwitcher.addEventListener('click', ()=>{
  themeSwitcher.checked ? document.body.classList.add('dark-theme') : document.body.classList.remove('dark-theme')
})


submitURL = (e, strategy) =>{
  e.preventDefault()
  let url = urlInput.value;
  
  loader.classList.remove('d-none');
  try {
    new URL(url);
  } catch (_) {
    urlInput.classList.add('wrong-url')
    console.log('url inválida')
    return false;  
  }
  urlInput.classList.remove('wrong-url')
  urlInput.classList.add('correct-url')
  
  setTimeout(() =>{
    urlInput.classList.remove('correct-url')
  }, 1000);
  
  strategy.forEach( strategy => {
    callApi(url,strategy);
  });

  resetFields()
}


resetFields = () =>{
  urlInput.value = '';
}

callApi = async (url,strategy) =>{
  let apiUrl = `${baseApiUrl}${url}&strategy=${strategy}&key=${apiKey}`;
  const response = await fetch(apiUrl);
  const data = await response.json();
  loader.classList.add("d-none")

  results.push(data)

  results.forEach(result =>{
    ulResults.innerHTML = `
    <section class="${result.lighthouseResult.configSettings.emulatedFormFactor}-strategy">
    Your website overall ${result.lighthouseResult.configSettings.emulatedFormFactor} performance is ${result.loadingExperience.overall_category}.
    </section>
    `
  })
}
*,
*:focus{
  outline: none;
}

input.wrong-url{
  border: 3px solid red;
}
input.correct-url{
  border: 3px solid green;
}

body{
  color: #322c3d;
  transition: background-color .9s;
}
body.dark-theme{
  background-color: #322c3d;
  color: #fff;
}
body.dark-theme .btn-custom{
  background-color: #9c5def;
  color: #322c3d;
}
input#urlInput{
  display: block;
  width: 100%;
  padding: 15px;
  margin: 1rem 0;
}
.data-wrap{
  height: 100vh;
}
.btn-custom{
  display: block;
  width: 100%;
  border: 0;
  padding: 15px;
  margin: 1rem 0;
  transition: background-color .9s;

}

.switcher-wrapper{
  text-align: right;
}

.d-none{
    display: none !important;
}

#loader {
  border: 16px solid #f3f3f3; 
  border-top: 16px solid #9c5def; 
  border-radius: 50%;
  width: 120px;
  height: 120px;
  animation: spin 3s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.mobile-strategy,
.desktop-strategy{
  max-width: 294px;
  padding: 15px;
}
.desktop-strategy{
  background: rgb(88, 8, 219, 0.5);
}
.mobile-strategy{
  background: rgb(88, 8, 219, 0.1);
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>PageSpeed</title>
  <link rel="stylesheet" href="./style.css">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
</head>
<body>

  <div class="container">
   <div class="data-wrap d-flex flex-column align-items-center justify-content-center">
    <form>
      <div class="switcher-wrapper">
        <label for="theme-switcher">Theme Switcher</label>
      <input type="checkbox" id="theme-switcher" name="theme-switcher">
      </div>
      <input 
      type="text" 
      name="URL"
      placeholder="URL"
      id="urlInput"
      >
      <div>
        Select the strategy:
        <input type="checkbox" id="mobile" name="mobile">
        <label for="mobile">Mobile</label>
        <input type="checkbox" id="desktop" name="desktop">
        <label for="desktop">Desktop</label>
      </div>
  
      <button 
      class="btn-custom"
      type="submit"
      id="analyzeUrl"
      onclick="submitURL(event, strategy)"
      >Run</button>
    </form>
    <div id="loader" class="d-none"></div>

    <div id="results">
      
    </div>

   </div>
  </div>
  <script src="base.js"></script>
</body>
</html>

Could someone help me fix this problem?

Andreas
  • 21,535
  • 7
  • 47
  • 56
Augusto Mallmann
  • 461
  • 1
  • 5
  • 10
  • Should it be `ulResults.innerHTML +=` instead of `=`? – adiga Dec 09 '20 at 13:56
  • `.innerHTML = ...` overwrites the content. You have to add (`+=`) it, or even better get rid of `.innerHTML` and use `.insertAdjacentHTML()` instead – Andreas Dec 09 '20 at 13:56

0 Answers0