devedv
devedv

Reputation: 622

Netinfo connectionChange event listener not getting detached

I have added connectionChange event listener on splash screen componentDidMount, but it is not removed on componentwillUnmount. It is active on every page of the application. How can I detach it on componentWillUnmount.

componentDidMount() {
         NetInfo.addEventListener('connectionChange',
    (networkType)=> {
        this.handleFirstConnectivityChange({networkType})
    }
}

    componentWillUnmount() {
        this.notificationListener.remove();
        NetInfo.removeEventListener(
            'connectionChange'
          );

}

Upvotes: 1

Views: 2064

Answers (2)

surendra ediga
surendra ediga

Reputation: 113

import OfflineNotice anywhere this works fine and please note u can see this working only in a physical device, not in the simulator

import React, { useEffect } from 'react';
import { View, Text, Dimensions, StyleSheet } from 'react-native';
import NetInfo from "@react-native-community/netinfo";
const { width } = Dimensions.get('window');

function MiniOfflineSign() {
return (
    <View style={styles.offlineContainer}>
        <Text style={styles.offlineText}>No Internet Connection</Text>
    </View>
);
}

let currentNetwork;

NetInfo.fetch().then(state => {
currentNetwork = state.isConnected;
});
const OfflineNotice = () => {
const [isConnected, setConnected] = React.useState(currentNetwork);
useEffect(() => {
    const unsubscribe =  NetInfo.addEventListener(state => {
        console.log("Is connected?", state.isConnected);
        setConnected(state.isConnected);

    });

    return unsubscribe
}, [])

return (
<>
      {!isConnected && (<MiniOfflineSign />)}
</>
 )
}

const styles = StyleSheet.create({
offlineContainer: {
    backgroundColor: '#b52424',
    height: 30,
    justifyContent: 'center',
    alignItems: 'center',
    flexDirection: 'row',
    width,
    position: 'absolute',
    top: 30
},
offlineText: { color: '#fff' }
});

export default OfflineNotice;

Upvotes: 0

jevakallio
jevakallio

Reputation: 35940

You need to pass the same callback you used in addEventListener to removeEventListener:

class SomeClass extends Component {
  handleConnectivityChange = networkType => {
    //...
  };

  componentDidMount() {
    NetInfo.addEventListener(
      "connectionChange", 
      this.handleConnectivityChange
    );
  }

  componentWillUnmount() {
    NetInfo.removeEventListener(
      "connectionChange", 
      this.handleConnectivityChange
    );
  }
}

Note that you shouldn't create a new arrow function wrapper when calling addEventListener, because you won't have a reference to that function instance, and you can't pass it to removeEventListener to unregister it. Instead, define the callback on the class instance, as above.

Upvotes: 4

Related Questions