0

I used the NetInfo library to detect whether the internet connection is available. It is working perfectly , but the snackbar inside the NetInfo function is not shown when internet is changed from on to off. Snackbar is shown perfectly when started with no internet and also started with internet. When Internet is changed from off to on every time, snackbar is shown every time BUT not shown when changed from ON to OFF. All the logs shows perfectly in every conditions. If I place a alertbox instead of snackbar, everything is perfect.

handleConnectivityChange = (isConnected) => {

  NetInfo.isConnected.fetch().done((isConnected) => {

    console.log('Dashboard ConnectivityChanged');

    console.log('IsConnectedValue:'+ isConnected );

    if(isConnected == true)
    {
        console.log('Dashboard Connected');

        Snackbar.show({
          title: 'Connected to Internet',
          duration: Snackbar.LENGTH_LONG,
          action: {
            title: 'DISMISS',
            color: 'rgb(216,21,88)',
            onPress: () => { /* Dismiss snackbar default */ },
          },
        });
    }
    else
    {
        console.log('Dashboard No Internet');

        Snackbar.show({
          title: 'No Internet Connection',
          duration: Snackbar.LENGTH_LONG,
          action: {
            title: 'DISMISS',
            color: 'rgb(216,21,88)',
            onPress: () => { /* Dismiss snackbar default */ },
          },
        });
    }
  });
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
Kamalesh kunwar
  • 262
  • 1
  • 5
  • 20

1 Answers1

0

I had a similar issue. Tbh I'm not sure what's causing it but as a temporary fix wrapping it inside a setTimeout seems to do the job, i.e.

setTimeout(() => {
  Snackbar.show({
      title: 'Connected to Internet',
      duration: Snackbar.LENGTH_LONG,
      action: {
        title: 'DISMISS',
        color: 'rgb(216,21,88)',
        onPress: () => { /* Dismiss snackbar default */ },
      },
    });
}, 1000);

Also, in order to prevent the Snackbar import throughout your app and code reusability, consider putting Snackbar.show() in a separate function.

Currently I have this in a utils.js that I call throughout my entire app:

export const showSnackbar = ({ title, duration = Snackbar.LENGTH_SHORT, action }) => {
  Snackbar.dismiss(); // dismiss if a snackbar is still "alive"
  if (!action) {
    Snackbar.show({
        title: message,
        duration,
    });
  } else {
    Snackbar.show({
        title,
        duration,
        action
    });
  }
};

Note that in the beginning I dismiss the previously shown snackbar if it's still on screen. Hope this helps :)

mstankov
  • 1
  • 1