Fetching and Displaying API Data in React Native
Your goal: Replace hardcoded book metadata with an HTTPS request, while keeping Book Details and local reading progress working.
Before you begin: Complete Navigation and Screen Parameters. Use that same Expo Router learning app, including its safe-area setup. This is Beginner Guide 09; code blocks belong in your Expo project, not in this statically generated website.
By the end, you will be able to:
- Explain requests, responses, status codes, JSON, and asynchronous work.
- Use
fetch,async/await, and explicit HTTP error handling. - Map external fields into a safe, small application model.
- Show loading, success, empty, error, retry, and refresh states.
- Cancel obsolete work and share one result between two routes.
Understand a request and response
An API (application programming interface) is a defined way for software to interact. A web API exposes URLs your app can request. REST is an architectural style that organizes resources behind URLs and uses HTTP methods to work with them. Here we use a read-only search endpoint: a GET request asks for information without asking the server to change it.
The app sends an HTTP request containing a URL and method. The server returns a response with a status, headers describing it, and a body containing data. HTTPS encrypts the connection. A status code describes the HTTP outcome:
| Status | Meaning for this lesson |
|---|---|
200 | The request succeeded; read its JSON body. |
404 | The requested endpoint or resource was not found. |
500 | The server encountered an error. |
429 | Too many requests; wait before trying again. |
A network error means Fetch could not obtain a usable response, for example because connectivity failed. A 500 is different: a server replied, but its reply reports failure. A successful search with no matches is different from both.
JSON is a text format for exchanging objects, arrays, strings, numbers, booleans, and null. Property names use double quotes; JSON cannot contain functions. response.json() reads that text and turns it into JavaScript values. It does not check that those values match your TypeScript types.
Network work is asynchronous because neither travel time nor server response time is predictable. The app can keep responding to touches while waiting. An await pauses its surrounding async function, not the whole interface.
Every completed attempt stops its loading indicator. A refresh failure keeps the last successful books and shows a message above them.
Choose a small public book search
We use the Open Library Search API: it supplies book metadata over HTTPS without an API key or login for this request. One search returns several books, so we do not fetch each selected book separately.
https://openlibrary.org/search.json?q=react%20native&limit=10&fields=key,title,author_name,first_publish_year
q supplies the search, limit=10 bounds the results, and fields requests only four fields. encodeURIComponent will encode the query in our helper. The endpoint returned ten usable entries when checked on October 29, 2026; titles and ordering can change. This abbreviated entry came from that response:
{
"key": "/works/OL29898642W",
"title": "Fullstack React Native",
"author_name": ["Houssein Djirdeh", "Anthony Accomazzo", "Sophia Shoemaker"],
"first_publish_year": 2019
}
Follow Open Library’s usage guidelines. At the time checked, unidentified requests are limited to one per second, and identified requests to three per second. The service asks regular users to identify their application with a User-Agent and contact information and invites application registration. This occasional learning request needs no account setup. Do not copy a fake contact address into headers or assume browser clients can control User-Agent.
Keep this a small educational demonstration. Retain results in memory, avoid polling and repeated reloads, and wait before retrying a rate-limit error. The complete example spaces attempts with a short delay and prevents simultaneous requests within this provider. That is not a shared quota system across devices. Open Library is not intended as a production backend or bulk metadata source; consult its policies before expanding usage.
Try fetch before adding state
Study this standalone function first; the full app uses the helper below instead. If you try it, call it once from a temporary button handler, never during rendering.
async function inspectBooks() {
const url = 'https://openlibrary.org/search.json?q=react%20native&limit=10&fields=key,title,author_name,first_publish_year';
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Request failed (HTTP ${response.status}).`);
}
const data: unknown = await response.json();
console.log(data);
} catch (error) {
console.warn(error instanceof Error ? error.message : 'Request failed.');
} finally {
console.log('This attempt has finished.');
}
}
A Promise represents an eventual value or failure. fetch(url) returns a Promise for a response and defaults to GET. An async function also returns a Promise; await unwraps a fulfilled value or throws a rejection into catch. Reading the JSON body needs a second await.
response.ok is true for HTTP statuses 200–299. Fetch does not automatically reject for 404 or 500; we throw explicitly. catch handles network, HTTP, and JSON parsing failures here. finally runs after either outcome; it is where our full example stops loading. See React Native networking and Fetch response handling.
Map JSON into the app’s model
External names belong to the API; our names should fit the interface. We validate incoming JSON as unknown before using it, instead of asserting as Book[].
| Remote field | Application field | Handling |
|---|---|---|
key | id | Require a work key; remove /works/ to get a route-safe ID such as OL29898642W. |
title | title | Use “Untitled book” if absent or blank. |
author_name | author | Join valid author strings; otherwise use “Unknown author”. |
first_publish_year | firstPublishYear | Keep a finite number when supplied. |
| None | Local read status | Store separately by book ID; never send it to Open Library. |
The helper defines a small SearchDocument for the fields we use after validation. Optional properties use ?. A missing or malformed docs array is an error, not an empty result. An invalid work key also produces an error so unusable records are not silently presented as “no matches.” Optional metadata can safely fall back.
Give both screens one owner
Previously, Home owned editable books and Details looked up metadata in initialBooks. An imported starting array cannot hold a live response. Move ownership above both routes:
RootLayout
BooksProvider: remote books + local readById + request state
Stack
Reading List → selected ID → Book Details
Context lets a parent provide values to descendants without passing props through every intermediate component. createContext defines the connection. A provider wraps part of the component tree and supplies a value to components inside it; useContext reads that value. Our tiny useBooks wrapper only reads that Context and checks for a missing provider. It is not a networking framework. See React Context.
Remote Book now describes metadata only. readById holds booleans keyed by stable ID. Refresh replaces metadata but does not reset progress, including toggles made while a refresh is in flight. Progress remains local and disappears on a full restart. The list still derives its count and progress bar during rendering.
Details reads the same in-memory books and makes no separate request. A direct details link starts the shared search once as the root mounts. It can display only books in that current ten-result search; missing, malformed, or unknown IDs get a friendly fallback. Arbitrary book deep links would require a separate lookup design, which we defer.
Follow the request lifecycle in React
Loading remote metadata synchronizes React with an external server, so it belongs in an Effect when the app mounts. In the provider below, useEffect calls loadBooks once on mount; Retry and Refresh call it directly from event handlers.
useCallback keeps loadBooks’s function identity stable. Its empty dependencies are appropriate because it uses imports, stable state setters, and refs, not changing props or state snapshots. The Effect depends on that function. Adding books to the dependencies would cause each response to trigger another request.
useRef stores the active controller across renders without rendering UI itself. A synchronous guard rejects overlapping attempts even before a disabled button has re-rendered. Cleanup calls abort(). Each continuation also checks signal.aborted, so canceled work cannot replace state or clear a newer request’s indicator. Cancellation is intentional and does not show an error; other failures still do. React Native provides AbortController.
The Effect itself is not async: it must return cleanup, not a Promise. Development Strict Mode may set up, clean up, and set up again; the canceled attempt stays silent. See React’s Effect reference.
| Situation | What the reader sees |
|---|---|
| First request or initial retry | ActivityIndicator and “Loading books…”; no empty message. |
| Success with books | Existing BookCard components inside FlatList. |
Success with docs: [] | A friendly ListEmptyComponent. |
| Failure before any success | Error and Retry; no misleading empty message. |
| Refresh after success | Existing results plus the pull-to-refresh indicator. |
| Refresh fails | Previous results plus an error and Retry. |
One phase value chooses loading, refreshing, or idle, so initial loading and refreshing cannot both be active. hasLoaded remembers whether any request succeeded, even if that success was empty. We retain that fact after refresh failures.
Run the complete application
What changes in this lesson: The list and Details now share fetched metadata and live reading progress. The original three hardcoded books are replaced by search results.
| File | Change from Navigation |
|---|---|
src/data/books.ts | Replace starting books with the metadata type and fetch helper. |
src/state/BooksProvider.tsx | Add the shared owner for results, read status, and request state. |
src/app/_layout.tsx | Wrap the stack with that provider. |
src/app/index.tsx and src/app/books/[id].tsx | Read shared state and show loading, retry, and missing-data messages. |
src/components/BookCard.tsx | Reuse unchanged. |
All six files are included below. Replace the previous lesson’s files and add the provider; do not combine the earlier fragments yourself. Keep the existing Expo configuration and dependencies, with src/app as the only route root. No new package is needed.
src/
app/
_layout.tsx
index.tsx
books/
[id].tsx
components/
BookCard.tsx
data/
books.ts
state/
BooksProvider.tsx
1. Fetch and map books
export type Book = {
id: string;
title: string;
author: string;
firstPublishYear?: number;
};
type SearchDocument = {
key: string;
title?: string;
author_name?: string[];
first_publish_year?: number;
};
const SEARCH_QUERY = 'react native';
const SEARCH_URL = 'https://openlibrary.org/search.json?q='
+ encodeURIComponent(SEARCH_QUERY)
+ '&limit=10&fields=key,title,author_name,first_publish_year';
function isObject(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function readDocument(value: unknown): SearchDocument {
if (!isObject(value) || typeof value.key !== 'string'
|| !/^\/works\/OL\d+W$/.test(value.key)) {
throw new Error('The book service returned an invalid book identifier.');
}
return {
key: value.key,
title: typeof value.title === 'string' ? value.title : undefined,
author_name: Array.isArray(value.author_name)
? value.author_name.filter((name: unknown): name is string =>
typeof name === 'string' && name.trim().length > 0)
: undefined,
first_publish_year: typeof value.first_publish_year === 'number'
&& Number.isFinite(value.first_publish_year)
? value.first_publish_year : undefined,
};
}
export async function fetchBooks(signal: AbortSignal): Promise<Book[]> {
const response = await fetch(SEARCH_URL, { signal });
if (!response.ok) {
throw new Error(response.status === 429
? 'The book service is busy. Wait a little before retrying.'
: `Could not load books (HTTP ${response.status}). Please try again.`);
}
const data: unknown = await response.json();
if (!isObject(data) || !Array.isArray(data.docs)) {
throw new Error('The book service returned an unexpected response.');
}
return data.docs.map((value: unknown): Book => {
const doc = readDocument(value);
return {
id: doc.key.replace('/works/', ''),
title: doc.title?.trim() || 'Untitled book',
author: doc.author_name?.map(name => name.trim()).join(', ') || 'Unknown author',
firstPublishYear: doc.first_publish_year,
};
});
}
Record<string, unknown> means an object with string keys whose values still need checking. The value is ... return types let TypeScript narrow values after those checks. ?. accesses a property only when its owner exists; || selects our fallback for an empty string. We keep the publication year in the model for an exercise.
2. Own state above the routes
import { createContext, useCallback, useContext, useEffect, useRef, useState } from 'react';
import type { ReactNode } from 'react';
import { fetchBooks } from '../data/books';
import type { Book } from '../data/books';
type Phase = 'loading' | 'refreshing' | 'idle';
type BooksValue = {
books: Book[];
readById: Record<string, boolean>;
phase: Phase;
hasLoaded: boolean;
error: string | null;
loadBooks: (refresh?: boolean) => Promise<void>;
toggleRead: (id: string) => void;
};
const BooksContext = createContext<BooksValue | null>(null);
export function BooksProvider({ children }: { children: ReactNode }) {
const [books, setBooks] = useState<Book[]>([]);
const [readById, setReadById] = useState<Record<string, boolean>>({});
const [phase, setPhase] = useState<Phase>('loading');
const [hasLoaded, setHasLoaded] = useState(false);
const [error, setError] = useState<string | null>(null);
const activeRequest = useRef<AbortController | null>(null);
const loadBooks = useCallback(async (refresh = false) => {
if (activeRequest.current) return;
const controller = new AbortController();
activeRequest.current = controller;
setPhase(refresh ? 'refreshing' : 'loading');
setError(null);
try {
// Space occasional attempts; do not hammer a public service.
await new Promise<void>(resolve => setTimeout(resolve, 1100));
if (controller.signal.aborted) return;
const nextBooks = await fetchBooks(controller.signal);
if (controller.signal.aborted) return;
setBooks(nextBooks);
setHasLoaded(true);
} catch (cause) {
if (controller.signal.aborted) return;
setError(cause instanceof Error ? cause.message : 'Could not load books. Please try again.');
} finally {
if (!controller.signal.aborted) {
activeRequest.current = null;
setPhase('idle');
}
}
}, []);
useEffect(() => {
void loadBooks();
return () => {
activeRequest.current?.abort();
activeRequest.current = null;
};
}, [loadBooks]);
function toggleRead(id: string) {
setReadById(previous => ({ ...previous, [id]: !previous[id] }));
}
return (
<BooksContext.Provider value={{ books, readById, phase, hasLoaded, error, loadBooks, toggleRead }}>
{children}
</BooksContext.Provider>
);
}
export function useBooks() {
const value = useContext(BooksContext);
if (value === null) throw new Error('useBooks must be inside BooksProvider.');
return value;
}
void loadBooks() says we are intentionally not awaiting the returned Promise in the Effect; loadBooks handles request failures internally. The 1,100 ms delay happens before every request, including the first load, Retry, and Refresh. It is a courtesy for this public-API demonstration, not a React Native or Fetch requirement, a request timeout, or a general rate-limit implementation. It does not coordinate separate provider instances, app reloads, or devices. If cleanup happens during that delay, the continuation wakes up, sees the aborted signal, and exits without fetching or changing state. The provider stays mounted while moving between these routes, so merely opening Details does not cancel or restart the search.
3. Wrap the existing stack
import { Stack } from 'expo-router';
import { BooksProvider } from '../state/BooksProvider';
export default function RootLayout() {
return (
<BooksProvider>
<Stack>
<Stack.Screen name="index" options={{ title: 'Reading List' }} />
<Stack.Screen name="books/[id]" options={{ title: 'Book Details' }} />
</Stack>
</BooksProvider>
);
}
The native header still handles the top safe area and normal back navigation. Screen safe-area views cover the other three edges, as before.
4. Keep the accessible book card
The card still receives ordinary props. Its Details and read/unread actions remain separate sibling controls.
import { Pressable, StyleSheet, Text, View } from 'react-native';
type BookCardProps = {
title: string;
author: string;
isRead: boolean;
onToggleRead: () => void;
onOpenDetails: () => void;
};
export default function BookCard({ title, author, isRead, onToggleRead, onOpenDetails }: BookCardProps) {
const buttonLabel = isRead ? 'Mark as unread' : 'Mark as read';
return (
<View style={styles.card}>
<Pressable
style={({ pressed }) => [styles.bookRow, pressed && styles.detailsPressed]}
onPress={onOpenDetails}
accessibilityRole="button"
accessibilityLabel={'View details: ' + title}
>
<Text
style={styles.bookIcon}
accessible={false}
accessibilityElementsHidden={true}
importantForAccessibility="no"
>
📖
</Text>
<View style={styles.details}>
<Text style={styles.bookTitle}>{title}</Text>
<Text style={styles.author}>{author}</Text>
<Text style={styles.detailsLink}>View details →</Text>
</View>
</Pressable>
<Text style={[styles.status, isRead && styles.readStatus]}>
Status: {isRead ? 'Read' : 'Unread'}
</Text>
<Pressable
style={({ pressed }) => [styles.button, pressed && styles.buttonPressed]}
onPress={onToggleRead}
accessibilityRole="button"
accessibilityLabel={buttonLabel + ': ' + title}
>
<Text style={styles.buttonText}>{buttonLabel}</Text>
</Pressable>
</View>
);
}
const styles = StyleSheet.create({
card: {
padding: 16,
gap: 12,
backgroundColor: '#ffffff',
borderWidth: 1,
borderColor: '#cbd5e1',
borderRadius: 16,
},
detailsPressed: { opacity: 0.7 },
detailsLink: { color: '#1e40af', fontSize: 16, fontWeight: '600' },
bookRow: { minHeight: 48, flexDirection: 'row', alignItems: 'flex-start', gap: 12 },
bookIcon: { fontSize: 28, flexShrink: 0 },
details: { flex: 1, gap: 4 },
bookTitle: { color: '#0f172a', fontSize: 20, fontWeight: '600' },
author: { color: '#475569', fontSize: 16 },
status: {
alignSelf: 'flex-start',
maxWidth: '100%',
paddingHorizontal: 10,
paddingVertical: 6,
borderRadius: 8,
backgroundColor: '#e2e8f0',
color: '#334155',
fontSize: 14,
fontWeight: '600',
},
readStatus: { backgroundColor: '#dcfce7', color: '#166534' },
button: {
minHeight: 48,
padding: 12,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#1e40af',
borderRadius: 10,
},
buttonPressed: { backgroundColor: '#1e3a8a' },
buttonText: { color: '#ffffff', fontSize: 16, fontWeight: '600', textAlign: 'center' },
});
5. Render every request state
refreshing controls the native pull indicator; onRefresh starts a request while retaining the list. The visible Refresh button offers the same action to keyboard and screen-reader users and is useful on web. See FlatList’s refresh props.
import { useRouter } from 'expo-router';
import { ActivityIndicator, FlatList, Pressable, StyleSheet, Text, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import BookCard from '../components/BookCard';
import { useBooks } from '../state/BooksProvider';
export default function HomeScreen() {
const router = useRouter();
const { books, readById, phase, hasLoaded, error, loadBooks, toggleRead } = useBooks();
const busy = phase !== 'idle';
const completedCount = books.filter(book => readById[book.id]).length;
const progressPercent = books.length === 0 ? 0 : completedCount / books.length * 100;
return (
<SafeAreaView style={styles.screen} edges={['left', 'right', 'bottom']}>
<FlatList
data={books}
extraData={readById}
keyExtractor={book => book.id}
refreshing={phase === 'refreshing'}
onRefresh={() => { if (hasLoaded) void loadBooks(true); }}
alwaysBounceVertical
contentContainerStyle={styles.content}
renderItem={({ item }) => (
<BookCard
title={item.title}
author={item.author}
isRead={readById[item.id] ?? false}
onToggleRead={() => toggleRead(item.id)}
onOpenDetails={() => router.push({
pathname: '/books/[id]',
params: { id: item.id },
})}
/>
)}
ListHeaderComponent={
<View style={styles.header}>
<Text style={styles.heading} accessibilityRole="header">My Reading List</Text>
<Text style={styles.body}>Book metadata from Open Library</Text>
{hasLoaded && (
<>
<Text style={styles.body}>{completedCount} of {books.length} books read</Text>
<View
style={styles.progressTrack}
accessible
accessibilityRole="progressbar"
accessibilityLabel="Reading progress"
accessibilityValue={{ min: 0, max: 100, now: Math.round(progressPercent),
text: `${completedCount} of ${books.length} books read` }}
>
<View style={[styles.progressFill, { width: `${progressPercent}%` }]} />
</View>
</>
)}
{phase === 'loading' && (
<View style={styles.notice}>
<ActivityIndicator size="large" color="#1e40af" accessibilityLabel="Loading books" />
<Text style={styles.body} accessibilityLiveRegion="polite">Loading books…</Text>
</View>
)}
{phase === 'refreshing' && (
<Text style={styles.body} accessibilityLiveRegion="polite">Refreshing books…</Text>
)}
{error !== null && (
<View style={styles.notice}>
<Text style={styles.error} accessibilityRole="alert" accessibilityLiveRegion="polite">
{hasLoaded ? 'Could not refresh. Showing the last results. ' : ''}{error}
</Text>
<Pressable
onPress={() => { void loadBooks(hasLoaded); }}
disabled={busy}
accessibilityRole="button"
accessibilityLabel="Retry loading books"
accessibilityState={{ disabled: busy }}
style={({ pressed }) => [styles.button, (pressed || busy) && styles.dimmed]}
>
<Text style={styles.buttonText}>Retry loading books</Text>
</Pressable>
</View>
)}
{hasLoaded && error === null && (
<Pressable
onPress={() => { void loadBooks(true); }}
disabled={busy}
accessibilityRole="button"
accessibilityLabel="Refresh books"
accessibilityState={{ disabled: busy }}
style={({ pressed }) => [styles.button, (pressed || busy) && styles.dimmed]}
>
<Text style={styles.buttonText}>Refresh books</Text>
</Pressable>
)}
</View>
}
ItemSeparatorComponent={() => <View style={styles.separator} />}
ListEmptyComponent={hasLoaded && error === null && phase === 'idle' ? (
<View style={styles.notice}>
<Text style={styles.bookTitle}>No books found</Text>
<Text style={styles.body}>This search found no matches. Try another query in books.ts.</Text>
</View>
) : null}
/>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
screen: { flex: 1, backgroundColor: '#f1f5f9' },
content: { padding: 16, flexGrow: 1 },
header: { gap: 12, marginBottom: 20 },
heading: { color: '#0f172a', fontSize: 28, fontWeight: '700' },
body: { color: '#334155', fontSize: 16 },
bookTitle: { color: '#0f172a', fontSize: 20, fontWeight: '600' },
error: { color: '#991b1b', fontSize: 16 },
notice: { padding: 16, gap: 12, backgroundColor: '#ffffff', borderRadius: 16 },
separator: { height: 16 },
progressTrack: { height: 12, borderRadius: 6, backgroundColor: '#cbd5e1', overflow: 'hidden' },
progressFill: { height: '100%', backgroundColor: '#1e40af' },
button: { minHeight: 48, padding: 12, alignItems: 'center', justifyContent: 'center',
backgroundColor: '#1e40af', borderRadius: 10 },
buttonText: { color: '#ffffff', fontSize: 16, fontWeight: '600', textAlign: 'center' },
dimmed: { opacity: 0.65 },
});
extraData={readById} tells the list that rendering also depends on state outside its data array. ?? false makes a book unread until an entry exists for its ID. The progress count covers only the current results. A successful refresh can change that collection, but retained IDs keep their local status.
6. Look up the selected ID
Details waits for the shared first request before deciding that a valid-looking ID is missing. If loading failed, it offers Retry. A malformed ID gets a fallback immediately; we never interpolate it into a request URL.
import { useLocalSearchParams, useRouter } from 'expo-router';
import { ActivityIndicator, Pressable, ScrollView, StyleSheet, Text, View } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useBooks } from '../../state/BooksProvider';
export default function BookDetailsScreen() {
const { id } = useLocalSearchParams<{ id?: string | string[] }>();
const router = useRouter();
const { books, readById, phase, hasLoaded, error, loadBooks } = useBooks();
const validId = typeof id === 'string' && /^OL\d+W$/.test(id);
const book = validId ? books.find(candidate => candidate.id === id) : undefined;
const busy = phase !== 'idle';
function returnToReadingList() {
if (router.canGoBack()) router.back();
else router.replace('/');
}
return (
<SafeAreaView style={styles.screen} edges={['left', 'right', 'bottom']}>
<ScrollView contentContainerStyle={styles.content}>
<View style={styles.card}>
{book ? (
<>
<Text style={styles.heading} accessibilityRole="header">{book.title}</Text>
<Text style={styles.author}>{book.author}</Text>
<Text style={styles.body}>Status: {readById[book.id] ? 'Read' : 'Unread'}</Text>
<Text style={styles.body}>Return to your Reading List to change reading progress.</Text>
</>
) : validId && busy ? (
<>
<ActivityIndicator size="large" color="#1e40af" accessibilityLabel="Loading books" />
<Text style={styles.body} accessibilityLiveRegion="polite">Loading books…</Text>
</>
) : validId && error !== null ? (
<>
<Text style={styles.body} accessibilityRole="alert">{error}</Text>
<Pressable
onPress={() => { void loadBooks(hasLoaded); }}
accessibilityRole="button"
accessibilityLabel="Retry loading books"
style={({ pressed }) => [styles.button, pressed && styles.dimmed]}
>
<Text style={styles.buttonText}>Retry loading books</Text>
</Pressable>
</>
) : (
<>
<Text style={styles.heading} accessibilityRole="header">Book not found</Text>
<Text style={styles.body}>Choose a book from the current Reading List results.</Text>
</>
)}
<Pressable
onPress={returnToReadingList}
accessibilityRole="button"
accessibilityLabel="Return to Reading List"
style={({ pressed }) => [styles.button, pressed && styles.dimmed]}
>
<Text style={styles.buttonText}>Return to Reading List</Text>
</Pressable>
</View>
</ScrollView>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
screen: { flex: 1, backgroundColor: '#f1f5f9' },
content: { padding: 16 },
card: { padding: 16, gap: 12, backgroundColor: '#ffffff', borderWidth: 1,
borderColor: '#cbd5e1', borderRadius: 16 },
heading: { color: '#0f172a', fontSize: 28, fontWeight: '700' },
author: { color: '#475569', fontSize: 20 },
body: { color: '#334155', fontSize: 16 },
button: { minHeight: 48, padding: 12, alignItems: 'center', justifyContent: 'center',
backgroundColor: '#1e40af', borderRadius: 10 },
buttonText: { color: '#ffffff', fontSize: 16, fontWeight: '600', textAlign: 'center' },
dimmed: { opacity: 0.65 },
});
The route still passes only id, not an entire book object. The key suffix becomes one URL segment, for example /books/OL29898642W. Both screens look up that same ID. See Expo’s URL parameter reference and root layouts.
Run npx expo start in your learning app and open it on your device or simulator. Expect a brief loading state, up to ten book cards, working read/unread controls, and a Details screen with matching metadata and progress. These are catalog results, not recommendations about which technical books are current.
Check the behavior manually
A website build checks MDX and site links; it does not execute these React Native examples. In the learning app, walk through these cases without repeatedly hitting the public API:
| Try | Expected result |
|---|---|
| Open the app with connectivity | Loading appears, then cards replace it. |
| Mark a book read, open Details, and go back | Both screens agree; the list count stays correct. |
| Pull down on the list or press Refresh | Existing cards stay visible; only the refresh indicator appears. |
| Toggle a card during refresh | The status survives the new response for that same ID. |
| Start offline, then reconnect and press Retry | Error replaces initial loading; Retry can recover. A device may take time to report connectivity failure. |
| Go offline after a success and refresh | The last successful list remains with an error and Retry. |
Temporarily return [] from fetchBooks before its network call | Empty UI appears after loading; restore the helper afterward. |
Temporarily throw new Error('Practice failure') at the start of fetchBooks | Error UI appears without contacting the service; restore afterward. |
Open /books/not-a-book or a well-formed ID absent from the results | Friendly fallback and Return to Reading List work. |
| Repeatedly tap Refresh while an attempt is pending | The active-request guard admits only one attempt. |
| Reload during loading; inspect development logs | Cleanup cancels the old work without displaying a cancellation error. |
Use VoiceOver or TalkBack and larger text to review labels, messages, and the separate card actions. Check pull-to-refresh on a native device: browser pointer gestures do not reproduce all native refresh behavior. No simulator screenshot is needed to understand the expected states.
Troubleshoot common networking mistakes
| Mistake or symptom | What to check |
|---|---|
Forgetting await | fetch() gives a Promise, not a response. Await both Fetch and .json() inside an async function. |
Treating 404 or 500 as success | Check response.ok before mapping the body. |
| Assuming every author or title exists | Validate JSON and use readable fallbacks. Type annotations do not validate a server response. |
| A spinner remains after an error | Stop the current attempt in finally; canceled attempts must not clear a newer indicator. |
| Old results overwrite new ones | Prevent overlap and cancel on cleanup; check the signal before state updates. |
| “Network request failed” | Check connectivity, the exact hostname/path, and HTTPS. Mobile connectivity can disappear mid-request. |
| Requests repeat after every response | Inspect Effect dependencies. Do not depend on the result you update or a newly created callback each render. |
| An empty message appears while offline | Empty means a successful docs: [], not a caught error. Keep those states separate. |
HTTP 429 | Stop repeated attempts and wait. Do not add automatic retry loops. |
| Details still shows the old three books | Replace its initialBooks import with useBooks, and wrap the stack with one provider. |
Do not switch to HTTP or disable transport protections to fix a URL problem. If experimenting on Expo web, browser cross-origin rules also apply; native and web environments can report different connectivity errors. This lesson does not need a connectivity-detection library.
Practice
- Change the search. Edit
SEARCH_QUERYto a favorite author or subject and reload once. Compare titles, author arrays, and missing fields. Keep the ten-result limit. - Show a publication year. Display
firstPublishYearon Details when available. Decide what to show when it is absent; do not renderundefinedor invent a date. - Improve recovery copy. Rewrite the Retry label or empty-state message to make the next action clearer. Keep accessibility labels consistent with the visible action.
Check your understanding
- Why can an awaited Fetch call succeed even when the response status is
500? - Why do we validate
docsbefore callingmap? - What distinguishes “no matches” from “could not load”?
- Why do we check an abort signal in
finallyas well as after Fetch? - Why is the provider above the stack, and why is read status separate from remote metadata?
- What limits which books a direct Details URL can display in this example?
Compare your answers
Fetch can fulfill with an HTTP error response, so we check response.ok ourselves. JSON could have any shape; validating docs prevents unsafe access and avoids treating malformed data as empty. No matches is a successful empty array, while a failure has an error message. An obsolete attempt must not clear a later attempt’s loading state. The provider lets both routes read one response; a separate read-status map protects local interactions from metadata refreshes. Direct links can resolve only IDs in the current search results, because this lesson has no individual-book lookup.
You are ready to continue when: You can explain each request state, recover from a failure, and open a fetched book’s details without issuing a second request or losing reading progress.
We intentionally defer pagination, live search, persistent storage, authentication, automatic retry/backoff, production caching, and broader networking architecture. Return to the learning path for the published sequence.