Search code examples
javascriptreact-nativeinternet-connection

Internet Connection Listener


I have an application which scans 2D barcodes then retrieves data from the URLs provided by the codes. In the event that the user loses connection to the internet, the application begins to store the URLs via AsyncStorage. The issue is, I need to implement a listener that upon regaining an internet connection, the application begins a given method. Are there any recommended ways to go about implementing a connection listener such as this?

Edit:
I have tried using a NetInfo EventListener however I am not sure if I'm using it incorrectly, as it always calls the passed function, even when the internet status hasn't changed.

_connectionHandler = (e) => {
    this.setState({ cameraActive: false })
    NetInfo.getConnectionInfo().then((connectionInfo) => {

        if (connectionInfo.type === "none"){
            console.log("No internet")
            dataArray.push(e.data)
            let barcodeData_delta = {
                data: dataArray
            }

            AsyncStorage.mergeItem(STORAGE_KEY, JSON.stringify(barcodeData_delta));

            NetInfo.isConnected.addEventListener(
                'connectionChange',
                this._handleConnectionChange(e.data)
            );
            this.setState({ cameraActive: true })
        } else {
            console.log("Internet available -> Going to read barcode now")
            this._handleBarCodeRead(e.data);
        }
    })
}

Solution

  • React Native has a NetInfo documentation, there you can see how to add a listener his connection changes, and do what you want when its called.

    Add a Handler to isConnected property

    NetInfo.isConnected.addEventListener(
      'connectionChange',
      _connectionHandler
    );
    

    A function that handles the change, just adjust your setState with the camera, I couldn't figure out when to call it.

    _connectionHandler = (isConnected) => {
        this.setState({ cameraActive: false })
            if (!isConnected){
                console.log("No internet")
                dataArray.push(e.data)
                let barcodeData_delta = {
                    data: dataArray
                }
                AsyncStorage.mergeItem(STORAGE_KEY, JSON.stringify(barcodeData_delta));                   
                this.setState({ cameraActive: true })
            } else {
                console.log("Internet available -> Going to read barcode now")
                this._handleBarCodeRead(e.data);
            }
        })
    }