skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search