What is the method to connect to a local API using Expo and React Native?

I’m running a FastAPI instance on localhost:8000, but when I attempt to retrieve data using the Fetch API, I encounter this error:

NetworkError when attempting to fetch resource.

This issue arises while using the web version of Expo (http://localhost:19006/). Here’s my code snippet:

const fetchUserProfile = async () => {
    try {
        const apiResponse = await fetch('http://localhost:8000/api/profile', {
            method: 'GET',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
        });
        const resultData = await apiResponse.json();
        updateUserData(resultData);
    } catch (fetchError) {
        updateErrorState(fetchError);
    } finally {
        toggleLoading(false);
    }
};

When I switch the fetch URL to a public API like https://dummy.restapiexample.com, everything works fine, indicating the issue is related to accessing my local API. What steps should I take to successfully connect to local APIs in Expo?

The issue arises because the emulator can’t access localhost of your PC. Try using your local IP address instead. Here’s how:

const fetchUserProfile = async () => {
    try {
        const apiResponse = await fetch('http://your_local_ip:8000/api/profile', {
            method: 'GET',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
        });
        const resultData = await apiResponse.json();
        updateUserData(resultData);
    } catch (fetchError) {
        updateErrorState(fetchError);
    } finally {
        toggleLoading(false);
    }
};

Replace your_local_ip with your machine’s IP (use ipconfig or ifconfig to find it). Ensure both devices are on the same network.