Blog>
Snippets

Conditional Data Fetching Based on Network Status

Develop a mechanism to fetch data from a local cache if the network is down and re-fetch from the server when the connection is back online.
function fetchData() {
  if (!navigator.onLine) {
    // Assume loadCacheData is a function that retrieves data from local cache
    return loadCacheData().then(data => {
      console.log('Loaded data from cache:', data);
      return data;
    });
  }
  // fetchDataFromServer is a function that performs a server fetch
  return fetchDataFromServer().then(data => {
    console.log('Fetched data from server:', data);
    return data;
  });
}
This function checks the online status of the navigator. If offline, it retrieves data from the local cache; if online, it fetches data from the server.
window.addEventListener('online', function() {
  // Call fetchData when the network status changes to online to refresh data from server
  fetchData().then(data => {
    console.log('Network is back online, fetched latest data:', data);
  });
});
An event listener is added to the window object that listens for the 'online' event, which triggers the `fetchData` function to refresh data from the server when network connection is restored.
window.addEventListener('offline', function() {
  console.log('Network offline, working from cache.');
});
An event listener is added for the 'offline' event to log when the network goes offline. It doesn't call `fetchData` since the function will be called automatically on any data request while offline.
function loadCacheData() {
  // This should be implemented to retrieve cached data
  // For this example, it returns a Promise resolving to mock data
  return Promise.resolve({ cached: 'data' });
}
Mock implementation of `loadCacheData` function. It should be replaced with the actual logic to retrieve cached data.
function fetchDataFromServer() {
  // This should be implemented to fetch data from the server
  // For this example, it uses fetch API to get data from a URL
  return fetch('https://api.example.com/data').then(response => response.json());
}
Mock implementation of `fetchDataFromServer` function. It should be replaced with actual server-side fetching logic, in this case using the `fetch` API to retrieve data from an example API endpoint.