Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 71 ยท State and Data

Networking with fetch

Load JSON in React Native with fetch: loading and error states, response.ok, AbortController timeouts, localhost addresses on emulators and HTTPS rules.

Almost every app talks to a server: it loads a feed, signs a user in, uploads a photo. React Native includes the same fetch function you know from the browser, so a first request looks familiar. What changes on a phone is everything around it: the network comes and goes, requests can hang for a long time, localhost means something different inside an emulator, and the operating system has strict rules about unencrypted traffic.

This lesson covers a robust way to call fetch, how to model loading and error states, how to cancel and time out a request, and the address and security rules that surprise newcomers.

What runs on this site. The real network layer of a phone cannot run here, so the React Native code is read-only. The runnable examples use a fake fetch: a function that returns a promise after a delay, with routes that succeed, return 404 or 500, or fail like a dead network. The state logic around it is exactly what you would write in an app.

A first request

fetch takes a URL and returns a promise of a Response. You then read the body, usually with response.json(), which is also a promise.

JSX
async function loadUser(id) {
  const response = await fetch(`https://api.example.com/users/${id}`);
  const user = await response.json();
  return user;
}

This works, but it hides three problems that appear in every real app. Fix them now and you will not have to hunt them later.

Three traps in a bare fetch

404 is not an error fetch only rejects when the network fails.
No loading state The screen shows nothing while waiting.
No timeout A stalled request can wait a very long time.

A good request helper handles all three.

1 / 2

fetch does not reject on 404

The promise returned by fetch rejects only when the request could not complete at all, for example when the device is offline. If the server answers with status 404 or 500, fetch still resolves. You must look at the response yourself:

JSX
async function getJson(url, options) {
  const response = await fetch(url, options);
  if (!response.ok) {
    // ok is true for status 200-299
    throw new Error(`Request failed with status ${response.status}`);
  }
  return response.json();
}

A failed network request in React Native rejects with TypeError: Network request failed. Invalid JSON makes response.json() throw as well. A single try/catch around getJson therefore covers all the failure kinds.

Loading, success and error

Keep the request in one piece of state that always has exactly one status. That avoids impossible combinations such as "loading and showing an error". Here is the pattern with the standard hooks:

JSX
import { useEffect, useState } from 'react';
import { ActivityIndicator, Text, View, Button } from 'react-native';

function UserScreen({ id }) {
  const [state, setState] = useState({ status: 'loading' });

  useEffect(() => {
    const controller = new AbortController();
    setState({ status: 'loading' });

    getJson(`https://api.example.com/users/${id}`, { signal: controller.signal })
      .then((data) => setState({ status: 'success', data }))
      .catch((error) => {
        if (error.name === 'AbortError') return; // we cancelled it ourselves
        setState({ status: 'error', message: error.message });
      });

    return () => controller.abort(); // leaving the screen cancels the request
  }, [id]);

  if (state.status === 'loading') return <ActivityIndicator />;
  if (state.status === 'error') return <Text>{state.message}</Text>;
  return <Text>{state.data.name}</Text>;
}

The cleanup function matters on mobile. A user can leave a screen before the response arrives, and without cancelling, the result would try to update a screen that no longer exists, and a request would keep a radio busy for nothing.

Run the same state machine below against a fake fetch. Pick a route, and try turning the response.ok check off to see what a 404 turns into.

Loading, success and error with a fake fetch

With the check on, /users/999 ends in the error state. With the check off, it reports "success" and the "data" is the server's error body. That is the bug the ok check prevents.

Cancelling and timing out

fetch has no timeout option. The standard tool is an AbortController: you pass controller.signal to fetch, and calling controller.abort() makes the promise reject with an error whose name is "AbortError". A timeout is just an abort scheduled with setTimeout:

JSX
async function fetchWithTimeout(url, ms = 10000) {
  const controller = new AbortController();
  const timer = setTimeout(() => controller.abort(), ms);
  try {
    return await fetch(url, { signal: controller.signal });
  } finally {
    clearTimeout(timer);
  }
}

(Some helper APIs such as AbortSignal.timeout exist in newer browsers, but do not assume every JavaScript engine in your app supports them. A setTimeout works everywhere.) Cancellation is also the right answer to a search box: when the user types another letter, abort the previous request so an old, slow response cannot arrive last and overwrite a newer one.

Timeout and cancel with AbortController

Sending data

POST requests need a method, headers and a body. Always stringify JSON yourself and set the content type:

JSX
const response = await fetch(`${API_URL}/notes`, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    Authorization: `Bearer ${token}`,
  },
  body: JSON.stringify({ title: 'Buy milk' }),
});

Uploading a photo uses FormData, where a file is described by an object with uri, name and type. Do not set the Content-Type header yourself for FormData; the runtime adds the correct multipart boundary.

Two differences from the browser are worth remembering. There is no CORS in a native app: the browser's same-origin rules do not apply, so you will never see a CORS error from a phone (the server's CORS headers only matter for your web build). And requests are always made by the operating system's network stack, which is where the address and security rules come from.

Axios: an alternative to fetch

fetch is built in, but many projects use Axios, a small HTTP library that works in React Native. It does not replace the ideas above; it changes the defaults.

Terminal
npm install axios
JSX
import axios from 'axios';

const api = axios.create({
  baseURL: 'https://api.example.com',
  timeout: 8000,
  headers: { Accept: 'application/json' },
});

// Request interceptor: add the token to every call
api.interceptors.request.use((config) => {
  const token = getToken();
  if (token) config.headers.Authorization = `Bearer ${token}`;
  return config;
});

// Response interceptor: one place to handle 401s
api.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response?.status === 401) signOut();
    return Promise.reject(error);
  },
);

async function loadAdvice() {
  const { data } = await api.get('/advice', { params: { lang: 'en' } });   // data is already parsed JSON
  return data;
}

What you gain compared to bare fetch:

Topic fetch Axios
JSON body JSON.stringify and res.json() yourself automatic both ways
HTTP errors (404, 500) resolves; you check res.ok rejects, with error.response.status
Timeout AbortController timeout option
Base URL and shared headers write a wrapper axios.create
Interceptors write a wrapper built in
Cancel AbortController AbortController signal option

The rejecting behavior is the biggest difference, and it is why try/catch around an Axios call also catches 404. A hand-written fetch wrapper can give you the same features in 20 lines, and one dependency fewer; choose Axios when you want the interceptors and conventions your team already knows.

What interceptors and error rejection do (stand-in)

The request interceptor adds the Authorization header once for every call. A 401 reaches the response interceptor, which signs the user out and still rejects, so the caller's catch runs.

Reading a local JSON file

Data that ships inside the app (a list of countries, a quiz, a seed catalogue) does not need a network request. Metro can import a .json file like a module:

JSX
import countries from './data/countries.json';       // parsed at build time

function Countries() {
  return (
    <FlatList
      data={countries}
      keyExtractor={(c) => c.code}
      renderItem={({ item }) => <Text>{item.name}</Text>}
    />
  );
}

That is the simplest and fastest option; the file is part of the JavaScript bundle, so keep it small (a few hundred KB at most; bigger data belongs in SQLite or on a server). require('./data/countries.json') works the same way. The data is read-only and updated only with an app release.

To read files at runtime (a file the user picked, a download) use a file-system module: expo-file-system, for example FileSystem.readAsStringAsync(uri) followed by JSON.parse. App files live in FileSystem.documentDirectory (kept) and FileSystem.cacheDirectory (the OS may clear it). Libraries such as react-native-fs give a similar API in bare projects, with constants for storage directories (DocumentDirectoryPath, ExternalStorageDirectoryPath on Android) and methods such as readFile and readDir. Android scoped storage means you generally cannot browse arbitrary folders like /storage/emulated/0/; use the system file picker (expo-document-picker) and read the file it returns.

Which address do I call?

While developing, your API often runs on your own computer. But localhost always means "the device I am running on", and that is not your computer once the app runs in an emulator or on a phone.

Where the app runs Address of the API on your computer
iOS Simulator http://localhost:3000
Android Emulator http://10.0.2.2:3000 (the emulator's alias for your host)
Real phone on the same Wi-Fi http://192.168.1.20:3000 (your computer's LAN address)
Production https://api.yourapp.com

Do not scatter these strings through your code. Put the base URL in one place, driven by configuration (in Expo, variables prefixed with EXPO_PUBLIC_ are inlined into the bundle, and they are public, so never put secrets there):

JSX
export const API_URL = process.env.EXPO_PUBLIC_API_URL ?? 'https://api.yourapp.com';

HTTPS and cleartext rules

Modern phones refuse plain http:// traffic to ordinary servers unless you opt in. iOS enforces App Transport Security, which requires HTTPS. Android 9 and newer block cleartext HTTP by default. Development builds often loosen these rules so the Metro dev server works, which is exactly why an http:// URL can work on your desk and then silently fail in a store build. The fix is not to switch the rule off, but to serve your API over HTTPS. If you must talk to a local http:// server during development, configure that exception only for debug builds (in Expo, through a config plugin such as expo-build-properties), and remove it before release.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A server answers a fetch call with status 404. What does the fetch promise do?

    fetch rejects only when the request could not complete, such as a network failure. An HTTP error status still resolves, so check response.ok yourself.
  2. 2. How do you give a fetch request a timeout?

    fetch has no timeout option. An AbortController scheduled with setTimeout makes the promise reject with an AbortError.
  3. 3. Which address reaches the API running on your computer from the Android Emulator?

    Inside the emulator, localhost is the emulator itself. 10.0.2.2 is the special alias the Android emulator provides for the host computer.
  4. 4. Why should a screen abort its request in a useEffect cleanup function?

    Aborting on unmount stops wasted work and prevents late responses from updating state of a screen that is gone. You still handle the AbortError in catch.

Summary

  • fetch resolves for any HTTP response; throw an error yourself when response.ok is false, and expect TypeError: Network request failed when the network is down.
  • Model a request as one status: loading, success or error, and always offer a retry for errors.
  • Use AbortController to cancel on unmount, to cancel superseded searches, and (with setTimeout) to implement timeouts.
  • Native apps have no CORS, but localhost differs per environment: 10.0.2.2 on the Android Emulator, your LAN address on a real device.
  • Serve production APIs over HTTPS; cleartext HTTP is blocked by default and development exceptions must not ship.
  • On this site the real network is read-only; the demos use a fake fetch with the same state logic.

Next, let a library handle caching and retries with Server State with TanStack Query.