In your opinion this is the right approach:
const [isNetwork, setIsNetwork] = useState(true);
const [isChangeNetwork, setIsChangeNetwork] = useState(false);
useEffect(() => {
NetInfo.fetch().then(({ isConnected, isInternetReachable }) =>
setIsNetwork(isConnected && isInternetReachable)
);
const unsubscribe = NetInfo.addEventListener(
({ isConnected, isInternetReachable }) => {
setIsNetwork(isConnected && isInternetReachable);
setIsChangeNetwork(true);
});
return () => unsubscribe.remove();
}, []);
...
<Snackbar
visible={isChangeNetwork}
onDismiss={() => setIsChangeNetwork(false)}
duration={3000}
theme={{ colors: { inverseSurface: isNetwork ? 'green' : 'red' } }}>
{isNetwork ? "Internet" : "No Internet"}
</Snackbar>
First I get the error: here: return () => unsubscribe.remove();
Visual studio also tells me:
Property 'remove' does not exist in type 'NetInfoSubscription'.ts(2339)
Can you suggest me a better method?
One problem is that when starting the app, even if there is internet, the Snackbar appears and says there is internet.
Instead I want the Snackbar to appear only in these cases:
- It is not there when starting the app
- There is a change of state, like here for example:
a) First there is internet (then nothing appears), then there is no internet (then the Snackbar appears)
b) First there is no internet (then the Snackbar appears), then there is the internet (then the Snackbar appears)
Can you give me a hand?
2
Answers
Your logic is correct, the only thing is to use
unsubscribe();
instead
unsubscribe.remove();
For my project I made custom hook of netInfo, it works fine for me you can try using below code with your snackBar,
useNetInfo.js ::::::Custom Hook
App.js