6.1 Fetching Data from APIs in React Native
Chapter Overview: In this chapter, you will learn how to fetch data from APIs in React Native applications. We will cover both Fetch API and Axios, handle responses, errors, and loading states. You will also see practical examples of rendering API data in your app using FlatList and ScrollView.
Meta Title: Fetching Data from APIs in React Native | React Native Tutorial
Meta Description: Learn how to fetch data from APIs in React Native using Fetch API and Axios. Handle responses, errors, and display data using FlatList and ScrollView. Practical examples included.
✅ Introduction to API Fetching
Fetching data from external APIs is essential for modern apps. APIs provide dynamic content like users, products, news, or posts. React Native allows you to fetch data easily using built-in fetch or third-party libraries like Axios.
✅ Using Fetch API
The fetch function is built into JavaScript. It returns a Promise which resolves to the response of the HTTP request.
import React, { useEffect, useState } from 'react';
import { View, Text, ActivityIndicator, FlatList } from 'react-native';
export default function UsersList() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/users')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => setUsers(data))
.catch(err => setError(err))
.finally(() => setLoading(false));
}, []);
if (loading) return <ActivityIndicator size="large" color="#007bff" />;
if (error) return <Text>Error: {error.message}</Text>;
return (
<FlatList
data={users}
keyExtractor={item => item.id.toString()}
renderItem={({item}) => <Text>{item.name} ({item.email})</Text>}
/>
);
}
Explanation:
- We use
useEffectto fetch data when the component mounts. loadingstate shows a spinner while data is being fetched.errorstate handles any network or API errors.FlatListefficiently renders a scrollable list of data.
✅ Using Axios for API Requests
Axios is a popular library that simplifies HTTP requests with better syntax and automatic JSON parsing.
import React, { useEffect, useState } from 'react';
import { View, Text, FlatList, ActivityIndicator } from 'react-native';
import axios from 'axios';
export default function UsersListAxios() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
axios.get('https://jsonplaceholder.typicode.com/users')
.then(res => setUsers(res.data))
.catch(err => setError(err))
.finally(() => setLoading(false));
}, []);
if (loading) return <ActivityIndicator size="large" color="#007bff" />;
if (error) return <Text>Error: {error.message}</Text>;
return (
<FlatList
data={users}
keyExtractor={item => item.id.toString()}
renderItem={({item}) => <Text>{item.name} ({item.email})</Text>}
/>
);
}
Tips:
- Use Axios when you need automatic JSON parsing and cleaner syntax.
- Always handle
loadinganderrorstates for better UX. - Use
FlatListinstead of mapping arrays for better performance with large datasets.
✅ Advanced Fetching Techniques
- Pagination: Fetch data page by page to improve performance.
- Pull-to-Refresh: Use
RefreshControlwithScrollVieworFlatList. - Handling headers: Pass authentication tokens using
headers. - Retry logic: Retry failed API requests for better reliability.
✅ Summary
- Fetching data is a crucial part of any React Native app.
- Both
fetchandAxioscan be used for HTTP requests. - Always handle loading and error states.
- Render data efficiently using
FlatListorScrollView. - Advanced techniques like pagination, headers, and retry improve user experience.
