Lesson 14 of 20Article18 min
Fetching Data & REST APIs
Use fetch (built-in) or axios for HTTP requests. Handle loading, success, and error states explicitly. Never assume the network is fast or available — mobile users switch between WiFi and cellular constantly.
Networking in React Native
Use fetch (built-in) or axios for HTTP requests. Handle loading, success, and error states explicitly. Never assume the network is fast or available — mobile users switch between WiFi and cellular constantly.
API data flow
API service layer
Typed API client
const BASE_URL = "https://api.example.com";
export async function apiGet<T>(path: string, token?: string): Promise<T> {
const res = await fetch(BASE_URL + path, {
headers: {
"Content-Type": "application/json",
...(token ? { Authorization: `Bearer ${token}` } : {}),
},
});
if (!res.ok) throw new Error(`API error ${res.status}`);
return res.json();
}
// Usage in screen:
const [posts, setPosts] = useState<Post[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
apiGet<Post[]>("/posts")
.then(setPosts)
.catch((e) => setError(e.message))
.finally(() => setLoading(false));
}, []);Best practices
- Centralize API calls in services/ — screens only call hooks.
- Use custom hook useFetch(url) to DRY loading/error logic.
- Set timeout with AbortController for slow networks.
- Show ActivityIndicator while loading; retry button on error.