1

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));
  }, []);
Md.Shakil Shaikh
  • 347
  • 4
  • 11
  • Use ngrok for simulating you localhost as a valid server for others and then try. For sure it will. – Kailash Sep 05 '22 at 12:08

2 Answers2

0

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 call

10.0.2.2 for Android or 127.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

Laurenz Honauer
  • 254
  • 1
  • 12
  • Still not working.I am trying to make calls from an android phone – Md.Shakil Shaikh Sep 05 '22 at 12:13
  • Then that is the reson. When you want to access `localhost`from your phone, the phone assumes you have a server running on the phone. What you need is some kind of config to bridge the network of your device with the network of your computer in order for this to work. Maybe [this](https://stackoverflow.com/a/11328581/11085515) helps. – Laurenz Honauer Sep 05 '22 at 13:37
0

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:

You are not able to access your local development server because that port hasn't been forwarded by ADB yet. When you run react-native run-android, React Native maps the port 8081 with your mobile device on USB. When you disconnect your USB you won't be able to refresh or hot reload your code anymore. So in this situation you can do 2 things, either map your local server port just like React Native does or use your local IP address

Do lemme know in case of any concerns

Gaurav Roy
  • 11,175
  • 3
  • 24
  • 45