0

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

Paul Angot
  • 11
  • 6

2 Answers2

1

There is a hook in the library that you can use out of the box, is called useNetInfo() and you can use it like this:

EDIT:

You can read this answer in order to use this hook into a class based app. This is similar to netInfo.

Example from git, react-native-community

import {useNetInfo} from "@react-native-community/netinfo";

const YourComponent = () => {
  const netInfo = useNetInfo();

  return (
    <View>
      <Text>Type: {netInfo.type}</Text>
      <Text>Is Connected? {netInfo.isConnected.toString()}</Text>
    </View>
  );
};

EDIT 2:

Full example:

import React from 'react'
import { SafeAreaView, Text } from 'react-native'
import { useNetInfo } from '@react-native-community/netinfo'

export default class Home extends React.Component {

    constructor(props) {
        super(props)
        this.state = {
            netInfo: undefined
        }
    }

    setNetInfo = netInfo => {
        this.setState({netInfo})
    }

    render () {

        return (
            <SafeAreaView>
                <SetNetInfo setNetInfo={this.setNetInfo} />
                <Text>Hello world</Text>
            </SafeAreaView>
        )
    }

}

const SetNetInfo = ({ setNetInfo }) => {
    const netInfo = useNetInfo()

    React.useEffect(() => {
        setNetInfo(netInfo)
    },[netInfo])

    return null
}
CevaComic
  • 2,056
  • 2
  • 6
  • 12
  • Thank you for your response ! I finally managed with another solution, but I really thank you for taking the time to post your examples, I'm pretty sure I'll use them afterwards, especially if I want to display a clear login status :) – Paul Angot May 25 '20 at 22:40
1

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

Tarik Chakur
  • 1,667
  • 13
  • 9