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';
  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. }
  10. // Code that you only run when network available, probably sync...
  11. }
Programming Language: ECMAScript