Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 38 ยท Data, Storage and Networking

Networking and API Calls in Expo

Call REST APIs from an Expo app with fetch: read JSON, handle HTTP errors, add timeouts with AbortController, retry safely and keep API URLs in environment variables.

Almost every app talks to a server: it loads a feed, sends a login, uploads a photo. In an Expo app you do this with the same fetch function you know from the browser. It is built into the JavaScript runtime (Hermes plus React Native's networking layer), so there is nothing to install.

What is different on a phone is the network itself. It is slow, it drops out in elevators, it switches from Wi-Fi to mobile data mid-request. This lesson shows how to write a small, careful API layer that copes with that.

What runs on this site. An Expo app needs a phone or simulator, so the real app code is shown read-only. The runnable examples are stand-ins: plain Node.js starts a real HTTP server on loopback and calls it with the same fetch API, so the request logic you see is the logic you would ship.

The basic request

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

export default function Users() {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    fetch('https://api.example.com/users')
      .then((response) => response.json())
      .then(setUsers);
  }, []);

  return (
    <View>
      {users.map((u) => <Text key={u.id}>{u.name}</Text>)}
    </View>
  );
}

This works, but it is missing three things every real app needs: a loading state, an error state, and a way to stop the request when the screen goes away.

fetch does not throw on HTTP errors

The most common beginner bug: a 404 or 500 response is not an exception. fetch only rejects when the request could not be made at all (no network, DNS failure, timeout). So you must check response.ok yourself.

JavaScript
const response = await fetch(url);
if (!response.ok) {
  throw new Error(`Request failed with status ${response.status}`);
}
const data = await response.json();

A good API layer turns every failure into one error type so screens can handle them in one way.

Node.js A typed request helper

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice that the helper reads the JSON body even for failures, because many APIs put a useful message there.

Sending data

POST, PUT and PATCH send a body. Set the content-type header yourself and serialize with JSON.stringify.

JavaScript
await request('/posts', {
  method: 'POST',
  headers: { 'content-type': 'application/json' },
  body: JSON.stringify({ title: 'Hello', done: false }),
});

For file uploads, send a FormData object and do not set content-type yourself: the runtime adds the multipart boundary.

Timeouts and cancellation

fetch has no built-in timeout. On a bad mobile network a request can hang for a minute, so give every call a deadline with AbortController. The same controller lets a screen cancel its request when it unmounts.

Node.js Timeout with AbortController

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

In a component, create the controller inside useEffect and call controller.abort() in the cleanup function. That prevents "state update on an unmounted component" problems.

Retrying safely

Some failures are temporary: a dropped connection, a 503. Retrying with exponential backoff (wait 200 ms, then 400 ms, then 800 ms) gives the network time to recover without hammering the server. Retry only idempotent requests (GET, PUT, DELETE). Retrying a POST can create the same order twice.

flowchart LR
  A["Send request"] --> B{"Success?"}
  B -- "yes" --> C["Return data"]
  B -- "no, retryable" --> D["Wait (doubles each time)"]
  D --> E{"Attempts left?"}
  E -- "yes" --> A
  E -- "no" --> F["Throw error"]

A retry loop with backoff stops after a fixed number of attempts.

Base URLs and environment variables

Never hard-code https://api.example.com in twenty files. Keep it in one place and read it from an environment variable. In Expo, any variable that starts with EXPO_PUBLIC_ is inlined into your JavaScript at build time:

Terminal
# .env
EXPO_PUBLIC_API_URL=https://api.example.com
JavaScript
const API_URL = process.env.EXPO_PUBLIC_API_URL;

Remember that these values end up inside the app bundle, so anyone can read them. Never put secrets such as private API keys in EXPO_PUBLIC_ variables; keep those on your server. Lesson App config and environment variables goes deeper.

Checking connectivity

The expo-network package (or @react-native-community/netinfo) tells you whether the device is online. Use it to show an "Offline" banner, but still handle request failures, because "connected to Wi-Fi" does not mean "internet works".

JSX
import * as Network from 'expo-network';

const state = await Network.getNetworkStateAsync();
console.log(state.isConnected, state.isInternetReachable);

Security basics

  • Use HTTPS only. Modern iOS and Android block plain HTTP by default.
  • Send tokens in the Authorization header, and store them in SecureStore (next lesson).
  • Never log tokens or full responses with personal data.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A server answers with status 500. What does fetch do?

    fetch only rejects when no response could be obtained. HTTP error codes resolve normally.
  2. 2. How do you cancel a fetch after a deadline?

    fetch has no timeout option. AbortController signals the request to stop.
  3. 3. Which requests are safe to retry automatically?

    Repeating an idempotent request has the same effect as sending it once. Repeating a POST may duplicate data.
  4. 4. What is true about EXPO_PUBLIC_ variables?

    They are plain text in your JavaScript, so never store secrets in them.

Summary

  • Use the built-in fetch; check response.ok because HTTP errors do not throw.
  • Wrap requests in one helper that adds headers, parses JSON and throws a single error type.
  • Add timeouts and cancellation with AbortController.
  • Retry only idempotent requests, with growing delays.
  • Keep base URLs in EXPO_PUBLIC_ variables, and keep secrets off the device.

Next: Secure storage and AsyncStorage