25 April 2024

To run code in React Native only when a network connection is available, you can use the NetInfo module from the @react-native-community/netinfo package. This module allows you to subscribe to network connection changes and conditionally execute your code based on the current network status.

Source code viewer
  1. import NetInfo from '@react-native-community/netinfo';
  2.  
  3. export async function internetConnected() {
  4. // Run only when internet is connected.
  5. const netInfo = await NetInfo.fetch();
  6. if (!netInfo.isConnected) {
  7. return;
  8. }
  9.  
  10. // Code that you only run when network available, probably sync...
  11. }
Programming Language: ECMAScript