how to use Netinfo in if statement in React Native Typescript

3.3k Views Asked by At

i need to use the NetInfo.isConnected in a variable to send to my if statement, but all examples i see in internet are the same, just console.log the value, never put inside a variable

function verifyConnection() {
  let isConnected;
  NetInfo.fetch().then((state) => {
    isConnected = state.isConnected;
  });
  return isConnected;
}

always return undefined, but if a put into a variable like this

let isConnected = NetInfo.fetch().then((state) => {state.isConnected});

return : LOG {"_A": null, "_x": 0, "_y": 0, "_z": null}

how to use netinfo inside a if statemente to test my connection status

1

There are 1 best solutions below

0
user18309290 On BEST ANSWER

Use async and await to wait a promise to resolve

async function verifyConnection() {
  return (await NetInfo.fetch()).isConnected;
}

or useNetInfo hook when rendering components.

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

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