Home > Back-end >  Refreshing async requests/ async with event listener
Refreshing async requests/ async with event listener

Time:02-11

I was wondering how to refresh an async request. For example, I have this code and I want to see a different message every time i click a button.

async function start() {
    const response = await fetch("https://www.boredapi.com/api/activity");
    const data = await response.json();
    console.log(data)
    let html = `<p>${data.activity}</p>`
    document.querySelector('button').addEventListener('click', toDo.bind(this, html))
}

function toDo(html) {
    document.querySelector('.msg').insertAdjacentHTML('beforeend', html)
}
    
start()

As a "solution" I did this:

document.querySelector('button').addEventListener('click', toDo);
async function toDo() {
    const response = await fetch("https://www.boredapi.com/api/activity");
    const data = await response.json();
    let html = `<p>${data.activity}</p>`
    document.querySelector('.msg').insertAdjacentHTML('beforeend', html)
}

Not sure if it's an ok practice since it could take some time before you see a result. In my case there is a slight delay which is understandable.

CodePudding user response:

If you do not want a delay, you need to fetch the text before you need it and display it. Basic idea is load first one when page loads. After you display the new entry, you fetch the next text.

function textGen () {

  const updateElem = document.querySelector('.msg');

  let currentText = '';
  let isFetching = false;
  
  
  async function fetchText () {
    isFetching = true;
    const response = await fetch("https://www.boredapi.com/api/activity");
    const data = await response.json();
    currentText = data.activity;
    isFetching = false;
  }
  
  fetchText();
  
  return {
    addNext: function () {
      if (isFetching) return;
      const html = `<p>${currentText}</p>`;
      updateElem.insertAdjacentHTML('beforeend', html);
      fetchText();
    }
  }
}

const myTextGen = textGen();
document.querySelector("button").addEventListener("click", myTextGen.addNext);
<button>Next</button>
<div ></div>

  • Related