The Fetch API is used in React Native applications to communicate with web servers and APIs. It allows an application to send HTTP requests and receive data from a backend server.
For example, a mobile application can use Fetch API to get student data, course information, products, news, or other data from a server.
React Native App
↓
Fetch API
↓
Server
↓
JSON Response
↓
React Native App
Fetch API is a built-in JavaScript interface for making network requests. It can be used in React Native to communicate with APIs.
fetch("https://example.com/api/users");
The fetch() function returns a Promise that can be used to
process the server response.
Mobile applications often need data from a remote server.
Fetch API can be used for these HTTP operations.
The simplest Fetch request uses a URL.
fetch("https://example.com/api/users")
.then(response => response.json())
.then(data => {
console.log(data);
});
The response is converted into JSON before using the returned data.
The fetch() function returns a Promise.
fetch(url)
.then(response => {
return response.json();
})
.then(data => {
console.log(data);
});
The first then() handles the response and the second
then() receives the converted data.
Fetch requests can also be written using async and
await.
async function getUsers() {
const response =
await fetch(url);
const data =
await response.json();
console.log(data);
}
This syntax can make asynchronous code easier to read.
You can create a separate function to load data from an API.
async function loadUsers() {
const response =
await fetch(
"https://example.com/api/users"
);
const data =
await response.json();
return data;
}
When data needs to be loaded when a screen appears, Fetch API can be
used inside useEffect().
useEffect(() => {
fetchUsers();
}, []);
The empty dependency array means the effect runs when the component is initially rendered.
API data can be stored in state.
const [users, setUsers] =
useState([]);
After receiving data:
setUsers(data);
React Native then re-renders the screen with the updated data.
const [users, setUsers] =
useState([]);
useEffect(() => {
fetch(
"https://example.com/api/users"
)
.then(response =>
response.json()
)
.then(data => {
setUsers(data);
});
}, []);
This example requests data and stores it in state.
A response should be checked before processing its data.
const response =
await fetch(url);
if (!response.ok) {
throw new Error(
"Request failed"
);
}
The ok property indicates whether the HTTP response was
successful according to the Fetch API response status.
Many APIs return JSON data.
const response =
await fetch(url);
const data =
await response.json();
console.log(data);
The json() method reads the response and parses it as JSON.
const [name, setName] =
useState("");
useEffect(() => {
fetch(url)
.then(response =>
response.json()
)
.then(data => {
setName(data.name);
});
}, []);
The state value can then be displayed using a Text component.
<Text>
{name}
</Text>
Network requests may take time. A loading state can show the user that data is being loaded.
const [loading, setLoading] =
useState(true);
After the request completes:
setLoading(false);
The ActivityIndicator component can be displayed while data is loading.
{loading ? (
<ActivityIndicator />
) : (
<Text>
Data Loaded
</Text>
)}
Network requests can fail. Use try...catch when working with
async and await.
try {
const response =
await fetch(url);
const data =
await response.json();
} catch (error) {
console.log(error);
}
An error state can store a message when the request fails.
const [error, setError] =
useState("");
Inside the catch block:
catch (error) {
setError(
"Unable to load data"
);
}
async function loadUsers() {
try {
setLoading(true);
setError("");
const response =
await fetch(url);
if (!response.ok) {
throw new Error(
"Request failed"
);
}
const data =
await response.json();
setUsers(data);
} catch (error) {
setError(
"Unable to load users"
);
} finally {
setLoading(false);
}
}
The finally block can be used to stop loading after either
success or failure.
Fetch can also send data to a server using the POST method.
fetch(url, {
method: "POST",
headers: {
"Content-Type":
"application/json"
},
body: JSON.stringify({
name: "Rahul",
email: "rahul@example.com"
})
});
async function createUser() {
const response =
await fetch(url, {
method: "POST",
headers: {
"Content-Type":
"application/json"
},
body: JSON.stringify({
name: "Rahul"
})
});
const data =
await response.json();
console.log(data);
}
Headers provide additional information to the server.
const response =
await fetch(url, {
headers: {
"Content-Type":
"application/json"
}
});
Authentication APIs may also require authorization-related headers, depending on the API design.
A login form can send credentials to a backend API.
const response =
await fetch(
"https://example.com/api/login",
{
method: "POST",
headers: {
"Content-Type":
"application/json"
},
body: JSON.stringify({
email: email,
password: password
})
}
);
The server can validate the credentials and return an authentication result.
An education application can use Fetch API to retrieve course data.
async function loadCourses() {
const response =
await fetch(
"https://example.com/api/courses"
);
const courses =
await response.json();
setCourses(courses);
}
API data can be displayed using FlatList.
<FlatList
data={users}
keyExtractor={
item => item.id.toString()
}
renderItem={({ item }) => (
<Text>
{item.name}
</Text>
)}
/>
FlatList is useful when displaying larger lists of API data.
An application may need to reload data after a user performs an action.
async function refreshData() {
await loadUsers();
}
This function can be connected to a refresh button or another UI action.
Instead of repeating API URLs throughout an application, keep API configuration organized.
const API_URL =
"https://example.com/api";
fetch(
`${API_URL}/users`
);
For larger applications, API functions can be placed in dedicated service files.
response.json() when JSON is expected.response.ok.import React, {
useEffect,
useState
} from "react";
import {
View,
Text,
ActivityIndicator,
FlatList
} from "react-native";
export default function UsersScreen() {
const [users, setUsers] =
useState([]);
const [loading, setLoading] =
useState(true);
const [error, setError] =
useState("");
async function loadUsers() {
try {
setLoading(true);
setError("");
const response =
await fetch(
"https://example.com/api/users"
);
if (!response.ok) {
throw new Error(
"Request failed"
);
}
const data =
await response.json();
setUsers(data);
} catch (error) {
setError(
"Unable to load users"
);
} finally {
setLoading(false);
}
}
useEffect(() => {
loadUsers();
}, []);
if (loading) {
return (
<ActivityIndicator />
);
}
if (error) {
return (
<Text>
{error}
</Text>
);
}
return (
<FlatList
data={users}
keyExtractor={
item =>
item.id.toString()
}
renderItem={({ item }) => (
<View>
<Text>
{item.name}
</Text>
</View>
)}
/>
);
}
This example combines Fetch API, useEffect, useState, loading handling, error handling and FlatList.
| Concept | Purpose |
|---|---|
| fetch() | Creates a network request |
| Promise | Represents the eventual result of an asynchronous request |
| response.json() | Parses a JSON response |
| response.ok | Indicates whether the HTTP response was successful |
| GET | Commonly used to retrieve data |
| POST | Commonly used to send new data |
| Loading State | Indicates that a request is in progress |
| Error State | Stores or displays request errors |
User Opens Screen
↓
useEffect()
↓
Fetch API Request
↓
Server
↓
HTTP Response
↓
Check response.ok
↓
response.json()
↓
Store Data in State
↓
Render UI
↓
Display Data
If Request Fails
↓
Catch Error
↓
Update Error State
↓
Show Error Message
Fetch API is one of the fundamental tools for connecting a React Native application with backend services. Once you understand GET and POST requests, JSON responses, loading states and error handling, you can build applications that work with real server-side data.
fetch() returns a Promise.response.json() to parse JSON responses.async and await for readable asynchronous code.response.ok before processing important responses.Question: Which function is commonly used in React Native to make a network request?