I'm building a mobile app,for android and IOS platform and i try to connect the back with the front, but i face a timeout error for the request on IOS, when it's work for android.
here my code:
const Login = ({ navigation }) => {
const [openToggle, setOpenToggle] = useState(false);
const [user, setUser] = useState([]);
let baseURL = null;
Platform.OS === "android"
? (baseURL = "http://10.0.2.2:8000")
: (baseURL = "http://10.0.2.2:8000");
useEffect(() => {
const getAllUser = async () => {
try {
const users = await axios.get(`${baseURL}/api/user`);
console.log("test");
console.log(users.data);
setUser(users.data);
} catch (error) {
console.log("erreur", error);
}
};
getAllUser();
}, []);
I'm on a simulator for android and on real Iphone for IOS.
erreur [Error: timeout exceeded]
I'm on the same wifi network for the simulator and the iphone.
Any advice?
On android emulator 10.0.2.2 corresponds to the local machine. More Information Here That is why it works on android.
On iOS, iOS simulator is sharing local machine internet so localhost or 127.0.0.1 will point to your local machine.
So you have to use localhost or 127.0.0.1 on iOS.
If you are running your app on your iPhone/Android device you have to connect your phone with the same wifi network and use your machine ipaddress
Check this https://reactnative.dev/docs/running-on-device
Or you can get the machine ip from where the packager is loading from following code
import { NativeModules } from 'react-native';
const { scriptURL } = NativeModules.SourceCode;
const scriptHostname = scriptURL.split('://')[1].split(':')[0];