0

I want to clear the react native app data if my app is disconnected from internet for more than 5 min.

I am using react native NetInfo to check network connectivity status. Saving the time when app disconnected and checking when it will reconnect to internet. If interval is more than 5 min then I want to clear the app data.

My Code is:

class OfflineMessage extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      isConnected: true
    };
  }

  componentDidMount() {
    NetInfo.addEventListener((state) => {
      this.handleConnection(state.isConnected);
    });
  }

  componentWillUnmount() {
    NetInfo.removeEventListener((state) => {
      this.handleConnection(state.isConnected);
    });
  }

handleConnection = (isConnected) => {
  this.setState({ isConnected });

  if(!isConnected){
    this.startTimer();
  } else {
    this.checkElapsed();
  }
};

startTimer = async () => {
  try {
    console.log('Internet disconnected at: ');
    await AsyncStorage.setItem('time', JSON.stringify(Date.now()));

  } catch (error) {
    // console.log('Something went wrong', error);
  }
}

checkElapsed = async () => {
    try {
      let startTime =  await AsyncStorage.getItem('time');

      if(startTime){
        let endTime = Date.now();
        const elapsedTime = Math.floor((endTime -JSON.parse(startTime))/1000);
        if(elapsedTime > 5){
           alert("5 min is completed.");
           // Clear app data
         }
        console.log('Time elapsed'+ elapsedTime);
      }

  } catch (error) {
    // console.log('Something went wrong', error);
  }
}

Problem: Both the methods startTimer and checkElapsed called whenever connectivity status changes. What is wrong with this code.

if I modify given code as :

    state = {
      isConnected: true
    };

  componentDidMount() {
    this.unsubscribeFromNetInfo = NetInfo.addEventListener((state) => {
          this.handleConnection(state.isConnected);
      });
  }

  componentWillUnmount() {
     this.unsubscribeFromNetInfo();
  }

  handleConnection = (isConnected) => {
    console.log(isConnected);
    this.setState({ isConnected });
};

EventListener called multiple times and status changes frequently true false,true,false .

Ravi Sharma
  • 507
  • 6
  • 21

1 Answers1

1

Now, you are handling the NetInfo subscription wrong, according to https://github.com/react-native-community/react-native-netinfo#usage

You would have to do:

componentDidMount() {
    this.unsubscribeFromNetInfo = NetInfo.addEventListener(state => {
        this.handleConnection(state.isConnected);
    });
}

componentWillUnmount() {
    this.unsubscribeFromNetInfo();
}

Also, if you want to check for 5 minutes use:

if (elapsedTime > 5 * 60)

as your conversion

Math.floor((endTime - JSON.parse(startTime)) / 1000)

converts it to seconds not minutes.

In the current state, your app will trigger almost everything as the code only checks for 5 seconds.

Otherwise, the logic that you implemented itself should be working :)

Elias
  • 3,592
  • 2
  • 19
  • 42
  • One issue here ,NetInfo connectionChange will called multiple times, why? – Ravi Sharma Mar 05 '20 at 13:04
  • I think it is initially called when the module itself is not connected yet, and then after that once it's refreshed. This should not be a problem tough as it's under 5 minutes anyway right? – Elias Mar 05 '20 at 14:57
  • 1
    I just checked and logged NetInfo is the very root of the project and yes the listener is called twice. If this is an issue for you, (which I think it is) save the last state in the component and only trigger the handle if the differ – Elias Mar 05 '20 at 15:02
  • https://github.com/react-native-community/react-native-netinfo/issues/217#issuecomment-538337844 – Elias Mar 05 '20 at 15:04