I'm trying to create a robust pattern in my React Native app so that if Internet connection is not there, I won't make API calls but display a "Connection lost..." message.
I created the following util function and trying to incorporate it into my API calls using fetch
but it doesn't seem to hit the then
block after getting a response.
Here's the function that checks the connection:
import NetInfo from "@react-native-community/netinfo";
export const isConnectedToInternet = () => {
NetInfo.fetch().then(state => {
return state.isConnected;
});
};
And here's how I'm trying to use it:
import { isConnectedToInternet } from '../my-utils';
export const someApiCall = () => {
isConnectedToInternet()
.then(result => {
if(result) {
return (dispatch) => fetch ('https://myapi/someendpoint', fetchOptionsGet())
.then(response => {
// Process data...
})
} else {
Alert.alert('No Internet connection!');
}
})
};
Any idea why I'm not hitting the then
block or suggestions to make this a robust pattern?