JAVASCRIPT

Conditionally Fetch API Data Based on Network Status

Optimize web applications by making API requests only when an active internet connection is detected, improving user experience and resource usage in JavaScript.

function isOnline() {
  return navigator.onLine;
}

async function fetchWhenOnline(url, options = {}) {
  if (!isOnline()) {
    console.warn('Offline: API request aborted. Will try again when online.');
    return new Promise((resolve, reject) => {
      const handleOnline = async () => {
        window.removeEventListener('online', handleOnline);
        try {
          const response = await fetch(url, options);
          if (!response.ok) throw new Error(`HTTP error! Status: ${response.status}`);
          resolve(await response.json());
        } catch (error) {
          reject(error);
        }
      };
      window.addEventListener('online', handleOnline);
    });
  }

  try {
    const response = await fetch(url, options);
    if (!response.ok) throw new Error(`HTTP error! Status: ${response.status}`);
    return await response.json();
  } catch (error) {
    console.error('Error fetching data:', error);
    throw error;
  }
}

// Usage example:
// fetchWhenOnline('https://api.example.com/status')
//   .then(data => console.log('API Status:', data))
//   .catch(error => console.error('Failed to get API status:', error));

// To react to real-time network changes and re-fetch:
// window.addEventListener('offline', () => console.log('Application is now offline.'));
// window.addEventListener('online', () => {
//   console.log('Application is now online. Attempting to re-fetch critical data...');
//   // You might want to trigger fetches for data that was missed while offline
// });
How it works: This snippet provides a function `fetchWhenOnline` that checks the browser's network status (`navigator.onLine`) before attempting an API request. If the user is offline, it defers the request and sets up an event listener to automatically retry once the internet connection is restored. This prevents unnecessary failed network requests, conserves resources, and provides a smoother experience by making API calls only when they have a chance of succeeding. It also demonstrates how to listen for `online` and `offline` events globally.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs