Native Event Listener For network connection

Good Day All,

I realise this will be less of an issue for those in the US and Europe, I am looking at implementing a event listener to handle network drops and loss of signal. Is there a way of doing this. Users of my apps in South Africa constantly face difficulty in this regard.

As always appreciate your assistance.

Kind Regards,
Raymond

I have come up with the following solution, open to any improvements or thoughts.

import React, { useEffect, useState } from 'react';

export default function CustomUIComponent({ component, eventHandlers, appData, pageData, parentDataModel, pods, settings, definition, instanceId, elRef }) {
  const [isOnline, setIsOnline] = useState(navigator.onLine);

  useEffect(() => {
    const handleNetworkChange = (isOnline) => {
      setIsOnline(isOnline);
      if (eventHandlers['On Network Change']) {
        eventHandlers['On Network Change']({
          Network: isOnline
        });
      }
    };

    const handleOnline = () => handleNetworkChange(true);
    const handleOffline = () => handleNetworkChange(false);

    window.addEventListener('online', handleOnline);
    window.addEventListener('offline', handleOffline);

    // Initial trigger with current network status
    handleNetworkChange(navigator.onLine);

    return () => {
      window.removeEventListener('online', handleOnline);
      window.removeEventListener('offline', handleOffline);
    };
  }, [eventHandlers]);

  return (
    <div ref={elRef}>
      {isOnline ? (
        <span role="img" aria-label="Online" style={{ color: 'green' }}>🔵</span>
      ) : (
        <span role="img" aria-label="Offline" style={{ color: 'red' }}>đź”´</span>
      )}
    </div>
  );
}

The plan would be to store any “offline” Transactions in local storage and once online my little blue dot will handle the situation. As i said are there any better ways of doing this?

Kind Regards,
Raymond

Hello @Raymond_Woodley

I’d like to say that there is no better solution, but it will be a little self-confident.

Your solution is pretty straight and will cover a lot of cases(maybe all of them). And I could advise only one thing - it’s to take into account LocalStorage limitations, like:

  • it does not save data if the user is in incognito mode
  • it has a 5MB limit(depends on browser, but frequently no more than 5)
  • it’s not safe storage, browser extensions could steal data from LS

Hello @Dima Thank you hopefully the idea can help someone else here.