Check the React native application is connected to the Internet.

 In this blog, we are going to see how to check our react native application is connect with internet or not.

I have used @react-native-community/netinfo

npm i @react-native-community/netinfo

Two ways to check the network status,

  1. Check the Network status once
  2. Subscribe to get Network status(It will check every second and if changes occure it will intimate)

Check the Network status once

If you need to check the network status when you are trigging something,

EX: While making an API call, you need to check the network status and based on result we can perform action.

NetInfo.fetch().then(state => {
console.log("Connection type", state.type);
console.log("Is connected?", state.isConnected);
});

Subscribe to get Network status

This will notify you instantly when the network fails and back online.

EX: Consider YouTube, it will alter the user instantly when network fails.

const [isConnected, setIsConnected] = useState(true);

useEffect(() => {
const unsubscribe = NetInfo.addEventListener(state => {
setIsConnected(!!state.isConnected);
});

return () => {
unsubscribe();
};
}, []);

State.isConnected will give a network status.

Hope this will help you as well, Reach me in the comments if you have any queries

Comments

Popular posts from this blog

Creating a Circular File Download Progress Bar using SVG in React Native

Best Practices for React Native Development Don’t and Do’s Prem Yathvik