I can fetch data easily in a React app.But when I am going to fetch data in a React-Native app. It shows [AxiosError: Network Error]
error.
axios
.get(`http://localhost:8000/api/products`)
.then(res => setProducts(res?.data))
.catch(error => console.log(error));
}, []);
2
Answers
I assume you are trying to make the calls from an emulator?
If yes,
localhost
is not going to work. Depending on whether you are running ios or android you have to call10.0.2.2
for Android or127.0.0.1
for ios.(I know 127.0.0.1 should be the same as localhost, but it seems that is not the case in the ios emulator. Would be interesting to know why exactly that is the case)
A little more infos here
Hey you just cant connect directly localhost with your react-native develpoment since it already has a port assigned on which it runs.
You can check this article which explains greatly about how to cinfugyre.
React Native Android Fetch failing on connection to local API
Basically you have to map your port to via ADB
this is the exact quote:
Do lemme know in case of any concerns