I have this scenario using pure React Native without Expo: I am currently using @react-native-tethering
libraries (wifi and hotspot) from GitHub, and trying to populate inside a text paragraph the wifi’s or hotspot’s IP address.
So I have the App()
function in main tsx file like :
function App(): React.JSX.Element {
const isDarkMode = useColorScheme() === 'dark';
const backgroundStyle = {
backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,
};
return (
<SafeAreaView style={backgroundStyle}>
<ScrollView
contentInsetAdjustmentBehavior="automatic"
style={backgroundStyle}>
<Header />
<View
style={{
backgroundColor: isDarkMode ? Colors.black : Colors.white,
}}>
<Section title="Step One">
Edit <Text style={styles.highlight}>App.tsx</Text> Let's check what IP I
have currently: <Text style={styles.highlight}> {returnIpAddress()}</Text>
</Section>>
</View>
</ScrollView>
</SafeAreaView>
);
}
so since that tethering library has Promise functions (getDeviceIp()
, getMyDeviceIp()
), so I created a function which should pass to Text the current IP of device, like:
function returnIpAddress() {
const [IpAddress, setIpAddress] = useState<string | null>(null);
useEffect(() => {
const [stateHotspot, setStateHotspot] = useState<boolean | null>(null);
const [stateWifi, setStateWifi] = useState<boolean | null>(null);
TetheringManager.isWifiEnabled().then(wifiState => {
setStateWifi(wifiState ? true : false);
});
HotspotManager.isHotspotEnabled().then(hotspotState => {
setStateHotspot(hotspotState ? true : false);
});
if (stateHotspot) {
TetheringManager.getDeviceIP().then(wifiIP => {
setIpAddress(wifiIP);
});
} else if (stateWifi) {
HotspotManager.getMyDeviceIp().then(hotspotIP => {
setIpAddress(hotspotIP);
});
} else {
setIpAddress('0.0.0.0');
}
return () => IpAddress;
}, []);
return IpAddress;
}
to call it inside <Text></Text>
and get back the IpAddress; But I get error about using hooks, even it is a function like :
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
I tried also to call async ()
supposing I get asynchronously that IP value but it was not permitted.
In another sample project I made with React Native Expo where I created a component export function I made something similar, and that worked instead…
Maybe in React Native without Expo , does that hook run differently way? What would be the trick to obtain that IpAddress in text? Or maybe I just could have missed something?
Thanks!
Cheers!