React Native gives you the same fetch you call in a browser, installed as a global when the app starts, so a component can request data without importing anything. The API looks familiar, but a screen that loads data still has to decide what counts as a failure, because fetch resolves for a 500 response and rejects only when the request itself never completes. Getting that split right decides whether a failed request ends in an error message or in a spinner that never stops.
Key terms
RequestInit: the type of the optional second argument tofetch, which carries the method, headers, body and the other request options.response.ok: a boolean on theResponsethat is true only when the HTTP status is from 200 to 299.- whatwg-fetch: the polyfill React Native builds its
fetch,Headers,RequestandResponseglobals from.
One argument for GET, two for everything else
Pass fetch a URL alone and it makes a GET request, because GET is the default when no method is given. Its typed signature is fetch(input: RequestInfo, init?: RequestInit): Promise<Response>, where input is a URL string or a Request. Everything that changes the request goes in init. React Native's RequestInit type declares ten options: body, credentials, headers, integrity, keepalive, method, mode, referrer, window and signal. Headers can be a plain object of strings, an array of [name, value] pairs or a Headers instance.
A JSON POST sets three of those options: method: 'POST', Accept and Content-Type headers of application/json, and a body you serialize yourself. The createOrder helper makes that call:
tsxconst response = await fetch(`${API_URL}/orders`, { method: 'POST', headers: {Accept: 'application/json', 'Content-Type': 'application/json'}, body: JSON.stringify(order), });
After the call, createOrder checks response.ok and throws for any status outside 200 to 299 before it parses the body.
Why a 500 still resolves
fetch resolves as soon as the server answers, whatever the status. When the underlying request completes, the polyfill copies the server's HTTP status onto the Response and resolves, so a 404 or a 500 lands in your success path. Check response.ok before you treat the body as data, and use status and statusText for the error message.
Reading the body is a second asynchronous step. Response offers json(), text(), blob(), arrayBuffer() and formData(), and each returns a promise. json() reads the body as text and hands it to JSON.parse, so a body that isn't valid JSON, such as an HTML error page, makes that promise reject. A body can also be read only once: calling json() after text() on the same response rejects with a TypeError whose message is Already read.
In TypeScript, cast the parsed JSON to the response type you expect, as in (await response.json()) as OrdersResponse.
What lands in catch
Three kinds of failure reject the fetch promise itself:
- a network failure rejects with a
TypeErrorwhose message isNetwork request failed - a timeout rejects with a
TypeErrorwhose message isNetwork request timed out - a request aborted through the
signaloption rejects with aDOMExceptionnamedAbortError
A json() call that fails to parse and any error you throw after checking response.ok end up in the same catch. A rejection from fetch that nobody catches is dropped silently, so the screen gives no sign that anything went wrong. Keep await fetch(...) and await response.json() in the same try block, and one catch handles every case.
Keeping the loading flag honest
A screen that loads on mount usually tracks the data, an error and a loading flag. Start the flag as true, so the first render already shows an ActivityIndicator, and start the request from a useEffect with an empty dependency array.
The flag has to go back to false on every path out of the request. In the OrdersScreen component, that line sits in a finally block:
tsx} catch (e) { setError(e instanceof Error ? e.message : 'Request failed'); } finally { setLoading(false); }
finally runs after the try completes and after the catch handles an error, so a timeout, an offline device and a 500 response all end with the spinner gone. Put setLoading(false) at the end of the try instead and any rejection jumps past it to the catch, leaving the ActivityIndicator on screen for good.
The if (!response.ok) check in OrdersScreen throws before json() runs, so a 500 response with an HTML body produces your own message with the status code instead of a JSON parse error that says nothing about the server.
Code Examples
type Order = {id: string; productId: string; quantity: number};
type NewOrder = {productId: string; quantity: number};
const API_URL = 'https://api.example.com';
// fetch is a global in React Native, so there is no import
export async function createOrder(order: NewOrder): Promise<Order> {
const response = await fetch(`${API_URL}/orders`, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(order),
});
// A 4xx or 5xx response resolves, so check the status yourself
if (!response.ok) {
throw new Error(`Order failed with status ${response.status}`);
}
return (await response.json()) as Order;
}import {useEffect, useState} from 'react';
import {ActivityIndicator, FlatList, Text, View} from 'react-native';
type Order = {id: string; productId: string; quantity: number};
type OrdersResponse = {orders: Order[]};
const API_URL = 'https://api.example.com';
export function OrdersScreen() {
const [isLoading, setLoading] = useState(true);
const [orders, setOrders] = useState<Order[]>([]);
const [error, setError] = useState<string | null>(null);
const loadOrders = async () => {
try {
const response = await fetch(`${API_URL}/orders`);
if (!response.ok) {
throw new Error(`Server returned ${response.status}`);
}
const json = (await response.json()) as OrdersResponse;
setOrders(json.orders);
} catch (e) {
setError(e instanceof Error ? e.message : 'Request failed');
} finally {
setLoading(false);
}
};
useEffect(() => {
loadOrders();
}, []);
if (isLoading) {
return <ActivityIndicator />;
}
if (error) {
return <Text>Could not load orders: {error}</Text>;
}
return (
<View>
<FlatList
data={orders}
keyExtractor={item => item.id}
renderItem={({item}) => (
<Text>
{item.productId} x {item.quantity}
</Text>
)}
/>
</View>
);
}