Up to the last lesson, Mrs. Rini's Laundry order list came from sample data inside the app. From now on it comes over HTTP from the Laravel server behind Mrs. Rini's order board, and the server only sends the orders of the logged-in account. That is API integration. It's like Wulan phoning the shop: "Is my laundry done?" She has to know the right number, say her name so the cashier knows which order is hers, and be ready if nobody picks up, if it rings too long, or if there turns out to be no order. A request to an API is exactly the same: an address, an identity (a token), and an answer that can be slow, fail, or come back empty.
The orders API contract
These endpoints are added to the order board server (Laravel, routes/api.php, behind the auth:sanctum middleware):
| Request | Response |
|---|---|
GET /api/me/orders |
200 {"data":[{"id":"13","name":"Wulan","kg":2,"status":"Ironing"}]}: only the active orders of the logged-in account |
GET /api/orders/13 |
200 {"data":{"id":"13", ...}}. Another customer's order: 404 |
| without a valid token | 401 {"message":"Unauthenticated."} |
- Every request sends
Accept: application/jsonandAuthorization: Bearer <token>. The token comes from logging in. idis sent as a string andkgcomes from theweightcolumn, so the shape matchestype Orderinsrc/data/orders.tsexactly.- Without
Accept: application/json, Laravel treats the request as coming from a browser and tries to redirect to the login page. On an API with no route namedlogin, the result is a 500 errorRoute [login] not defined.
The server address per environment
Guess first: the Laravel server runs on your laptop with php artisan serve, at http://localhost:8000. The app in the Android emulator calls fetch('http://localhost:8000/api/me/orders'). What happens?
| The app runs on | The laptop's address | Why |
|---|---|---|
| Android emulator | http://10.0.2.2:8000 |
10.0.2.2 is an alias for the laptop's 127.0.0.1. localhost in the emulator = the emulator itself |
| iOS simulator | http://localhost:8000 |
the simulator uses the Mac's own network |
| A real phone, same Wi-Fi | http://192.168.100.96:8000 |
the laptop's IP on the Wi-Fi. Run php artisan serve --host=0.0.0.0, because its default 127.0.0.1 only accepts the laptop itself |
| The released app | https://api.rinislaundry.com |
HTTPS is required, see the last section |
So from the Android emulator, localhost:8000 points at the emulator itself, there is no server there, and the request fails to connect. Use 10.0.2.2. The address goes in .env.local at the project root:
# .env.local (kept out of git)
EXPO_PUBLIC_API_URL=http://10.0.2.2:8000
Variables starting with EXPO_PUBLIC_ are read through process.env.EXPO_PUBLIC_API_URL, and their values are baked into the JavaScript bundle. So never put a secret in one.
Fetching the orders: fetch and TanStack Query
// src/lib/api.ts
import * as SecureStore from 'expo-secure-store';
import type { Order } from '@/data/orders';
const API_URL = process.env.EXPO_PUBLIC_API_URL ?? 'http://localhost:8000';
export async function fetchMyOrders(): Promise<Order[]> {
const token = await SecureStore.getItemAsync('token'); // saved at login
const res = await fetch(`${API_URL}/api/me/orders`, {
headers: { Accept: 'application/json', Authorization: `Bearer ${token}` },
signal: AbortSignal.timeout(10_000), // no answer within 10 seconds: cancel
});
if (!res.ok) throw new Error(`Server answered ${res.status}`);
const body: { data: Order[] } = await res.json();
return body.data;
}
fetchis built into React Native. In Expo SDK 57, the globalfetchisexpo/fetch, and Expo addsAbortSignal.timeout.fetchhas no time limit of its own. On Android, React Native's built-in HTTP client is even set to no timeout, so a stuck server can keep the loading screen up forever.AbortSignal.timeout(10_000)cancels it after 10 seconds.fetchonly fails when the connection fails. A401or500response still counts as success, so checkres.okyourself.- The token is kept in
expo-secure-store(the Keychain on iOS, the Keystore on Android), not in ordinary storage. Details in the local storage lesson. - Axios works in React Native too and has its own
timeoutoption. Whichever you pick, pair it with TanStack Query for caching and retries.
// src/app/(tabs)/index.tsx
import { useQuery } from '@tanstack/react-query';
import { ActivityIndicator, Button, FlatList, Text, View } from 'react-native';
import { fetchMyOrders } from '@/lib/api';
export default function Orders() {
const { data, isPending, isError, error, refetch, isRefetching } = useQuery({
queryKey: ['orders', 'mine'],
queryFn: fetchMyOrders,
});
if (isPending) return <ActivityIndicator style={{ flex: 1 }} />;
if (isError) {
return (
<View style={{ flex: 1, justifyContent: 'center', padding: 16, gap: 12 }}>
<Text>Could not load orders: {error.message}</Text>
<Button title="Try again" onPress={() => refetch()} />
</View>
);
}
return (
<FlatList
data={data}
keyExtractor={(o) => o.id}
renderItem={({ item }) => <Text>#{item.id} {item.name}: {item.status}</Text>}
refreshing={isRefetching}
onRefresh={refetch}
ListEmptyComponent={<Text>No active orders yet.</Text>}
/>
);
}
Four screen states: loading (isPending), error (with a retry button), empty (ListEmptyComponent), and filled. When a request fails, TanStack Query tries again 3 times, waiting 1, 2, then 4 seconds. If the server always answers 500:
| Second | What happens |
|---|---|
| 0 | attempt 1: 500 |
| 1 | attempt 2: 500 |
| 3 | attempt 3: 500 |
| 7 | attempt 4: 500, isError becomes true, "Could not load orders: Server answered 500" shows |
Pull to refresh, and a status that changes
refreshing and onRefresh on a FlatList create the built-in RefreshControl: pull the list down, a spinner appears, refetch is called. Use isRefetching, not isLoading: isLoading is only true on the first load, so the pull-to-refresh spinner would never show.
GET /api/me/orders 200 {"data":[{"id":"13","name":"Wulan","kg":2,"status":"Ironing"}]}
(Mrs. Rini moves card #13 on the board)
(Wulan pulls the list down)
GET /api/me/orders 200 {"data":[{"id":"13","name":"Wulan","kg":2,"status":"Ready for pickup"}]}
Order #13's status changes from "Ironing" to "Ready for pickup" without closing the app. Other ways: reload when the app comes back to the front (focusManager from the state lesson), refetchInterval: 60_000 for every minute, or news straight from the server through realtime (the Realtime track) and push notifications (the next lesson).
Plain HTTP is blocked in release builds
- Android: since Android 9 (API 28), unencrypted HTTP (cleartext) is off by default. The output of
npx expo prebuildputsandroid:usesCleartextTraffic="true"only in the debug manifest, sohttp://10.0.2.2:8000works during development. In a release build, the same request is refused:CLEARTEXT communication to 10.0.2.2 not permitted by network security policy. - iOS: App Transport Security (ATS) requires HTTPS. The
Info.plistfrom prebuild holdsNSAllowsArbitraryLoads=falseandNSAllowsLocalNetworking=true: HTTP tolocalhost, IP addresses and.localnames is allowed, buthttp://api.rinislaundry.comis blocked. - So the real server must use HTTPS. Plain HTTP is only for the server on your laptop during development.
⚠️ Addresses, headers and tokens that often go wrong
localhostfrom the Android emulator or a real phone. It points at the phone itself. Use10.0.2.2in the emulator, the laptop's IP on a real phone (with--host=0.0.0.0).refreshing={isLoading}. The pull-to-refresh spinner never shows. UseisRefetching.- Not checking
res.ok. A401 {"message":"Unauthenticated."}response counts as success, andbody.dataends upundefined. Throw an error when!res.ok. - Forgetting
Accept: application/json. Laravel redirects to the login page, and an API with nologinroute answers 500. - A token in an
EXPO_PUBLIC_variable or ordinary storage. It can be read from the bundle or from the phone. Keep tokens inexpo-secure-store.
TL;DR: The app gets Wulan's orders from GET /api/me/orders (only the logged-in account's orders, {"data":[...]}), with Accept: application/json and Authorization: Bearer <token> from expo-secure-store. The server address per environment comes from EXPO_PUBLIC_API_URL: 10.0.2.2:8000 from the Android emulator (localhost in the emulator is the emulator itself), localhost from the iOS simulator, the laptop's IP from a real phone with php artisan serve --host=0.0.0.0. The recommended way: built-in fetch (or axios) plus TanStack Query for caching and retries (3 times, waiting 1, 2, 4 seconds). Check res.ok, set a time limit with AbortSignal.timeout, show the loading, error and empty states, and use refreshing={isRefetching} with onRefresh={refetch} for pull to refresh, which turns #13 from "Ironing" into "Ready for pickup". Plain HTTP only works in development: Android release builds (since Android 9) and iOS (ATS) block it, so the real server must use HTTPS.
⚡ localhost in the emulator
Write:
EXPO_PUBLIC_API_URL=http://10.0.2.2:8000
Guess first: the Laravel server runs on your laptop at http://localhost:8000. The app in the Android emulator calls that address. What happens?
It fails to connect. localhost in the emulator is the emulator itself, and there's no server there. 10.0.2.2 is an alias for the laptop's 127.0.0.1.
Meaning: The server address differs per environment, so put it in .env.local. EXPO_PUBLIC_ values are baked into the bundle, so never put a secret in one.
⚡ fetch plus TanStack Query
Write:
const { data, isPending, isError, error, refetch, isRefetching } = useQuery({
queryKey: ['orders', 'mine'],
queryFn: fetchMyOrders,
});
Meaning: Built-in fetch (or axios) sends the request, and TanStack Query handles caching and retries: a failed request is tried again 3 times, waiting 1, 2, then 4 seconds. Show the loading, error, empty and filled states.
⚡ A 401 still counts as success
Write:
if (!res.ok) throw new Error(`Server answered ${res.status}`);
Meaning: fetch only fails when the connection fails. A 401 or 500 response still counts as success, so check res.ok yourself. Send Accept: application/json too, or Laravel redirects to the login page.