Proposal: isConnected/isInternetReachable should NOT return false on first render.
See original GitHub issueDescribe the Feature
Current implementation of the useNetInfo hooks is kind of weird. Especially for slow connection. By default this 2 flags return false on the first render. If you have a naive component that use this to do some kind of
if (isInternetReachable) return <ErrorMessage />
else return <ActualComponentBody thatRequires="internet" />
You have for a very short moment, an error message. I would expect this hook instead to return “undefined” when things are actually unknown, instead of a false negative.
Currently if you do a native call of the hook & use your app in a poorly connected env, you can have a “false” for a few hundreds ms, which can show an error.
Instead of doing
- false
- then listen
I would do
- undefined
- fetch & update
- then listen
Possible Implementations
Here is something I am using. Adjusted for my needs as I only use isInternetReachable
.
// @flow
// https://github.com/react-native-netinfo/react-native-netinfo/issues/405
import * as React from 'react';
import NetInfo from '@react-native-community/netinfo';
import type { NetInfoState } from '@react-native-community/netinfo';
export default (): void | boolean => {
const [isInternetReachable, isInternetReachable_set] = React.useState(
undefined,
);
React.useEffect(() => {
const update = (state: NetInfoState) => {
// ignore first initialisation on iOS where it's null for a moment
if (
isInternetReachable === undefined &&
state.isInternetReachable === null
) {
return;
}
if (state.isInternetReachable !== isInternetReachable) {
isInternetReachable_set(() => state.isInternetReachable);
}
};
NetInfo.fetch().then(update);
return NetInfo.addEventListener(update);
}, [isInternetReachable]);
return isInternetReachable;
};
Related Issues
I detected a few issue that could be solved by a new implementation as I am recommending like #356, #254 and #295 and maybe indirectly issues like #352, #326
Issue Analytics
- State:
- Created 3 years ago
- Reactions:25
- Comments:7 (1 by maintainers)
Top GitHub Comments
@EhsanSarshar it’s open source, why wouldn’t you just PR something more reliable?
or you can do.