0

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

user20372455
  • 13
  • 1
  • 2

1 Answers1

1

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>
  );
};
user18309290
  • 5,777
  • 2
  • 4
  • 22