Polling for Updates with Fetch

October 2, 2024 ยท View on GitHub

human (Oct 1, 2024, 10:12 AM)

Write JavaScript (no React) that polls /updates/1/ using fetch() and takes the HTML from that and injects it into innerHTML in a div with id='updates'

assistant (Oct 1, 2024, 10:12 AM)

Here's a JavaScript code snippet that polls the /updates/1/ endpoint using fetch(), retrieves the HTML content, and injects it into a div with the id 'updates':

function pollUpdates() {
  fetch('/updates/1/')
    .then(response => response.text())
    .then(html => {
      document.getElementById('updates').innerHTML = html;
    })
    .catch(error => {
      console.error('Error fetching updates:', error);
    })
    .finally(() => {
      // Schedule the next poll after 5 seconds (5000 milliseconds)
      setTimeout(pollUpdates, 5000);
    });
}

// Start polling
pollUpdates();

This code does the following:

  1. We define a pollUpdates function that:

    • Uses fetch() to make a GET request to /updates/1/
    • Converts the response to text (HTML)
    • Injects the received HTML into the div with id 'updates'
    • Catches and logs any errors
    • Schedules the next poll after 5 seconds using setTimeout
  2. We call pollUpdates() to start the polling process.

This script will continuously poll the /updates/1/ endpoint every 5 seconds and update the content of the 'updates' div with the received HTML.

Would you like me to explain any part of this code in more detail?