I am creating an application in React Native with Expo and I am using USB debugging mode to see the view of this application.
The problem is that I am consuming an API, which is found locally on my computer. When I run the program with Expo from USB debugging mode I can't connect to localhost, but when I run the application with Expo web mode I can connect and consume the API.
Obviously I tried localhost and 127.0.0.1 but neither one worked for me.
For what it's worth: This would be my code:
import { StatusBar } from 'expo-status-bar';
import React, { Component, useState, useEffect } from 'react';
import { StyleSheet, Text, View, FlatList, ActivityIndicator, Image } from 'react-native';
const API_ENDPOINT = "https://127.0.0.1:5001/api/Medicines/";
export default function App () {
const [isLoading, setIsLoading] = useState(false);
const [data, setData] = useState([]);
const [error, setError] = useState(null);
useEffect(() => {
setIsLoading(true);
fetch(API_ENDPOINT)
.then(response => response.json())
.then(results => {
setData(results);
setIsLoading(false);
})
.catch(err => {
setIsLoading(false);
setError(err);
});
}, []);
if (isLoading) {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<ActivityIndicator size="large" color="#5500dc" />
</View>
);
}
if (error) {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text style={{ fontSize: 18}}>
Error fetching data... Check your network connection!
</Text>
</View>
);
}
return (
<View style={styles.container}>
<Text>Successful connection</Text>
<StatusBar style="auto" />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
I run the program in the cmd with the command expo start --localhost --android
to start the USB debugging mode and see the application from the Expo mobile application, and this is what appears to me:
And this is the same application but from the Expo web option: