react native how you handling your screens when internet is offline and then online? - react-native

I use 99% on my screens fetch. So if the connection is lost and data are not fetched my screen is empty. So when the internet is again online nothing happens.
So then I downloaded netInfo but if I disable my internet connection then my isOffline state is always false. Nothing happens, how can I detect on real time when internet is off/on?
const [isOffline, setIsOffline] = useState(false);
useEffect(() => {
const removeNetInfoSubscription = NetInfo.addEventListener((state: NetInfoState) => {
const offline = !(state.isConnected && state.isInternetReachable)
console.log(offline)
setIsOffline(offline)
})
return () => removeNetInfoSubscription()
}, [])
console.log(isOffline);

If you are using an old version of React Native, you might face this issue with netinfo. Downgrading the version of netinfo to v6 (or updating the React Native to version>=0.65) might make it work.
See this GitHub issue

Related

How can I obtain a reference to the URL that was used to open my app with a link in iOS

I have a problem with the situation where my React Native Expo app is running in the background / inactive modus and the app is brought back to the foreground / active mode as a result of the user opening a deep link to my app from the mobile browser.
When this situation occurs, my app needs to get a reference to the deep link in order to show the expected content to the user. The problem is that Linking.getInitialURL() always returns the link that was used to open the app from cold start and not the link that was used to bring the app back to foreground / active modus.
Advice on how to fix this problem would be greatly appreciated.
Found it out by myself :-)
useEffect(() => {
Linking.addEventListener('url', handleLinkEvent);
return () => {
Linking.removeEventListener('url', handleLinkEvent);
};
}, []);
For these cases you should use Linking.addEventListener
To complete #timboektoe's answer, react-navigation offers a subscribe function to listen to any URL received.
const subscribe = (listener) => {
const onReceiveURL = ({ url }) => { listener(url); };
const subscription = Linking.addEventListener('url', onReceiveURL);
return () => {
subscription.remove();
};
};
const linking = {
prefixes,
config,
getInitialURL,
subscribe,
};

useURL hook expo-linking for background app

The expo-linking React Native package has a hook named useURL that isn't working for me when the app is in the background. From the docs it Returns the initial URL followed by any subsequent changes to the URL. The problem I'm having with my managed expo app is that the hook doesn't work when the app is already open in the background. Here is the hook:
export default function App() {
const isLoadingComplete = useCachedResources();
const url = Linking.useURL();
useEffect(() => {
Alert.alert(url ? url.substring(20) : 'null');
}, [url]);
if (!isLoadingComplete) {
return null;
} else {
return (
...
);
}
}
If I open the URL exp://exp.host/#myprofile/myproject?a=bwhen the app is closed, I get an Alert as expected. If the app is in the background, the Alert doesn't go off. I've tested on an iOS emulator and a physical Android. Any solutions? Note that similar problems happen with Linking.addEventListener().

How to use setTimeout in react native?

Hi I working on a react native project I need to support my app offline.
I used NetInfo Library from expo documentation.
like below
const netInfo = useNetInfo();
const networkCheck = () => {
setTimeout(() => {
const net = netInfo.isInternetReachable;
console.log(net);
if (net === false) {
setloadCachedListings(true);
}
}, 2000);
};
networkCheck();
I want to wait for some time at this step of my code because this hook always returns null first time then after few milliseconds it tells the real network status.
But this code is not working as I an trying to do.
Is there any way to achieve this?
I just want to wait a little bit to get real network connection and then go further with my code.
logs for netInfo hook.

How to detect screenshots with React Native (both Android and iOS)

I am trying to detect if a user takes a screenshot while using a smartphone app that I have built. I am building my project with React Native.
I have been told that I can possibly prevent screenshots for Android but not for iOS. but can I still detect whether a user attempts to take a screenshot so that I can at least send a warning via Alert?
Thanks in advance
I tried react-native-screenshot-detector but it did not work
you can use this package it supports android&ios screenshot detecting react-native-detector
import {
addScreenshotListener,
removeScreenshotListener,
} from 'react-native-detector';
// ...
React.useEffect(() => {
const userDidScreenshot = () => {
console.log('User took screenshot');
};
const listener = addScreenshotListener(userDidScreenshot);
return () => {
removeScreenshotListener(listener);
};
}, []);
There is no package for it currently.

How to force users to update the app using react native

I have updated my app on app and play store and I want to force my app users to update the new version of app in App store and playstore.
You can check for the App Store / Play Store version of your app by using this library
react-native-appstore-version-checker.
In expo app you can get the current bundle version using Constants.nativeAppVersion. docs.
Now in your root react native component, you can add an event listener to detect app state change. Every time the app transitions from background to foreground, you can run your logic to determine the current version and the latest version and prompt the user to update the app.
import { AppState } from 'react-native';
class Root extends Component {
componentDidMount() {
AppState.addEventListener('change', this._handleAppStateChange);
}
_handleAppStateChange = (nextState) => {
if (nextState === 'active') {
/**
Add code to check for the remote app version.
Compare it with the local version. If they differ, i.e.,
(remote version) !== (local version), then you can show a screen,
with some UI asking for the user to update. (You can probably show
a button, which on press takes the user directly to the store)
*/
}
}
componentWillUnmount() {
AppState.removeEventListener('change', this._handleAppStateChange);
}
}
import VersionCheck from 'react-native-version-check';
i have used version check lib for this purpose and approach i used is below. if version is lower i'm opening a modal on which an update button appears, and that button redirects to app store/google play
componentDidMount() {
this.checkAppUpdate();
}
checkAppUpdate() {
VersionCheck.needUpdate().then(res => {
if (res.isNeeded) {
setTimeout(() => {
this.setState({openModal: true});
});
}
});
}
updateApp = () => {
VersionCheck.getStoreUrl({
appID: 'com.showassist.showassist',
appName,
})
.then(url => {
Linking.canOpenURL(url)
.then(supported => {
if (!supported) {
} else {
return Linking.openURL(url);
}
})
.catch(err => console.error('An error occurred', err));
})
.catch(err => {
console.log(`error is: ${err}`);
});
};
For future readers.
If you are using Expo managed workflow, install this package react-native-version-check-expo using yarn add react-native-version-check-expo or npm install react-native-version-check-expo.
Consult the package documentation on Github for usage guidelines.
I'm using react-native-version-check-expo library to achieve this. Working fine for me.
if you are looking for an easy to integrate built in solution. You can use App Upgrade https://appupgrade.dev/ service to force update your mobile apps.
Create new version entry for your app version that you want to update in the app upgrade service and select whether you want to force it or just want to let users know that new version is available.
Integrate your app with App Upgrade using available SDK. Official SDK are available for React Native, Flutter, Expo, Android and iOS(Swift).
The SDK will take care of the rest.
Whenever you want to force upgrade a version just create a version entry in app upgrade dashboard.
You can also integrate using API. Just call the appupgrade api from your app with the required details such as your app version, platform, environment and app name.
The API will return you the details.. that this app needs to be updated or not.
Based on the response you can show popup in your app.You can call this API when app starts or periodically to check for the update. You can even provide a custom message.
API response:
See the response has force update true. So handle in the app by showing popup.
You can find the complete user documentation here. https://appupgrade.dev/docs
Thanks.