react-nativehookreact-native-community-netinfo

Using @react-native-community/netinfo in a class, possible?


I'm trying to add to my application a function to add a view indicating to the user that he is disconnected from the internet network.

So I went to @react-native-community/netinfo to set it up but I quickly found myself confronted with the difficulty of using hooks and the related error: "Invalid hook call. Hooks can only be called inside of the body of a function component".

So how to integrate @react-native-community/netinfo on an application that is class based?

I would like to change the state of the application when the change of connection state is detected, to show or not the view indicating the disconnected state.

Your help would be greatly appreciated!

This is what I used for my tests:

enter image description here


Solution

  • I Guess (from the error message) you are declaring the listener in the class itself which is wrong.

    Just move the listener declaration to the componentDidMount hook and unsubscribe from it in componentWillUnmount hook, it should work as you would expect.

    If u need a full example leave a comment and I'll provide it to you. Cheers