The Fetch API is a built-in JavaScript feature used to send HTTP requests from a React Native application to a REST API. It can be used to retrieve, create, update, and delete data from a PHP/MySQL backend.
Fetch API is used to communicate with servers using HTTP requests.
fetch("https://example.com/api/students.php");
It returns a Promise that represents the result of the HTTP request.
Fetch can be used for:
fetch(url, options);
The first argument is the API URL.
The second argument is optional and can contain:
If no method is specified, fetch uses GET by default.
fetch("https://example.com/api/students.php")
.then(response => response.json())
.then(data => {
console.log(data);
});
The fetch() function does not immediately return the final API data. It returns a Promise.
const request = fetch(API_URL);
console.log(request);
The Promise is completed when the server responds.
One way to handle a Fetch Promise is with .then().
fetch(API_URL)
.then(response => {
return response.json();
})
.then(result => {
console.log(result);
});
async/await usually makes API code easier to read.
async function loadData() {
const response = await fetch(API_URL);
const result = await response.json();
console.log(result);
}
The first result returned by fetch is a Response object.
const response = await fetch(API_URL);
console.log(response.status);
console.log(response.ok);
The Response object contains information about the HTTP response.
Use response.json() to read a JSON response.
const response = await fetch(API_URL);
const result = await response.json();
console.log(result);
The result becomes a JavaScript object or array.
The PHP API might return:
{
"success": true,
"message": "Students retrieved successfully",
"data": [
{
"id": 1,
"name": "Rahul"
}
]
}
React Native can access each field after parsing the JSON.
const response = await fetch(API_URL);
const result = await response.json();
console.log(result.success);
console.log(result.message);
console.log(result.data);
This works well when the backend follows a consistent API response structure.
The response.ok property indicates whether the HTTP response has a successful status code.
const response = await fetch(API_URL);
if (response.ok) {
console.log("Request successful");
} else {
console.log("Request failed");
}
You can check the exact HTTP status code.
const response = await fetch(API_URL);
if (response.status === 200) {
console.log("OK");
}
if (response.status === 404) {
console.log("Not Found");
}
if (response.status === 500) {
console.log("Server Error");
}
The second fetch argument can contain request configuration.
fetch(API_URL, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: "Rahul"
})
});
The method option specifies which HTTP method should be used.
method: "GET"
method: "POST"
method: "PUT"
method: "PATCH"
method: "DELETE"
Headers provide additional information about the request.
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
}
Content-Type tells the server what format is being sent.
Use JSON.stringify() to convert a JavaScript object into JSON text.
const student = {
name: "Rahul",
email: "rahul@example.com"
};
const response = await fetch(API_URL, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(student)
});
Protected APIs can receive a JWT through the Authorization header.
const response = await fetch(API_URL, {
method: "GET",
headers: {
"Authorization": `Bearer ${token}`,
"Accept": "application/json"
}
});
Use try/catch with async/await to handle network-level errors.
try {
const response = await fetch(API_URL);
const result = await response.json();
console.log(result);
} catch (error) {
console.log(
"Network Error:",
error.message
);
}
Fetch does not automatically throw an error simply because the server returns HTTP 404 or 500.
const response = await fetch(API_URL);
if (!response.ok) {
throw new Error(
`HTTP Error: ${response.status}`
);
}
Therefore, check response.ok or response.status yourself.
try {
const response = await fetch(API_URL);
const result = await response.json();
if (!response.ok) {
throw new Error(
result.message || "Request failed"
);
}
console.log(result.data);
} catch (error) {
console.log(error.message);
}
API results can be stored in state.
const [students, setStudents] = useState([]);
async function loadStudents() {
const response = await fetch(API_URL);
const result = await response.json();
if (result.success) {
setStudents(result.data);
}
}
A loading state can be used while waiting for fetch to finish.
const [loading, setLoading] = useState(false);
async function loadStudents() {
setLoading(true);
try {
const response = await fetch(API_URL);
const result = await response.json();
setStudents(result.data);
} catch (error) {
console.log(error.message);
} finally {
setLoading(false);
}
}
if (loading) {
return (
<ActivityIndicator
size="large"
/>
);
}
This gives the user feedback while the API request is running.
useEffect() can call the API when the screen first loads.
useEffect(() => {
loadStudents();
}, []);
This pattern is commonly used for list and dashboard screens.
Query parameters can be added to the API URL.
const search = "Rahul";
const url =
`${API_URL}?search=${encodeURIComponent(search)}`;
const response = await fetch(url);
const result = await response.json();
This can be used for search, filtering, sorting, and pagination.
const page = 1;
const limit = 10;
const response = await fetch(
`${API_URL}?page=${page}&limit=${limit}`
);
const result = await response.json();
console.log(result.data);
console.log(result.meta);
The API can return both records and pagination metadata.
A reusable function can reduce repeated API code.
async function apiRequest(url, options = {}) {
const response = await fetch(
url,
options
);
const result = await response.json();
if (!response.ok) {
throw new Error(
result.message || "API request failed"
);
}
return result;
}
Usage:
const result = await apiRequest(API_URL);
console.log(result.data);
import React, {
useEffect,
useState
} from "react";
import {
View,
Text,
FlatList,
ActivityIndicator
} from "react-native";
const API_URL =
"https://example.com/api/students.php";
export default function StudentScreen() {
const [students, setStudents] = useState([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
async function loadStudents() {
setLoading(true);
setError("");
try {
const response = await fetch(API_URL);
const result = await response.json();
if (!response.ok) {
throw new Error(
result.message ||
"Unable to load students"
);
}
if (result.success) {
setStudents(result.data);
} else {
setError(result.message);
}
} catch (error) {
setError(error.message);
} finally {
setLoading(false);
}
}
useEffect(() => {
loadStudents();
}, []);
if (loading) {
return (
<ActivityIndicator
size="large"
/>
);
}
if (error) {
return (
<Text>
{error}
</Text>
);
}
return (
<View>
<FlatList
data={students}
keyExtractor={(item) =>
item.id.toString()
}
renderItem={({ item }) => (
<Text>
{item.name}
</Text>
)}
/>
</View>
);
}
This example combines fetch(), async/await, JSON parsing, HTTP error checking, loading state, error state, useEffect(), and FlatList.
Question: Which method is used to convert a Fetch API JSON response into a JavaScript object?