Lesson 97 of 158 – Fetch API
61%

Fetch API in React Native

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.

Note: React Native can use fetch() without installing an additional HTTP library. In this lesson, we will learn the basic Fetch API before using it for complete GET, POST, PUT, and DELETE operations.

1. What is the Fetch API?

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.

2. Why Use Fetch in React Native?

Fetch can be used for:

  • Loading students from an API
  • Submitting registration forms
  • Sending login information
  • Updating records
  • Deleting records
  • Searching API data
  • Loading paginated data
  • Accessing protected APIs

3. Basic Fetch Syntax

fetch(url, options);

The first argument is the API URL.

The second argument is optional and can contain:

  • HTTP method
  • Headers
  • Request body
  • Other request options

4. Simple GET Request

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);
    });

5. Fetch Returns a Promise

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.

6. Using .then()

One way to handle a Fetch Promise is with .then().

fetch(API_URL)
    .then(response => {
        return response.json();
    })
    .then(result => {
        console.log(result);
    });

7. Using async and await

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);
}

8. Understanding the Response Object

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.

9. Converting Response to JSON

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.

10. Example PHP JSON Response

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.

11. Accessing Response Data

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.

12. Checking response.ok

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");

}

13. Checking HTTP Status

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");
}

14. Fetch Options

The second fetch argument can contain request configuration.

fetch(API_URL, {
    method: "POST",
    headers: {
        "Content-Type": "application/json"
    },
    body: JSON.stringify({
        name: "Rahul"
    })
});

15. HTTP Method

The method option specifies which HTTP method should be used.

method: "GET"
method: "POST"
method: "PUT"
method: "PATCH"
method: "DELETE"

16. Request Headers

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.

17. Sending JSON Data

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)

});

18. Authorization Header

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"
    }

});

19. Handling Network Errors

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
    );

}

20. HTTP Errors vs Network Errors

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.

21. Complete Error Handling

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);

}

22. Fetch with React State

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);

    }
}

23. Loading State

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);

    }
}

24. Displaying a Loading Indicator

if (loading) {

    return (
        <ActivityIndicator
            size="large"
        />
    );

}

This gives the user feedback while the API request is running.

25. Loading Data with useEffect()

useEffect() can call the API when the screen first loads.

useEffect(() => {

    loadStudents();

}, []);

This pattern is commonly used for list and dashboard screens.

26. Query Parameters with Fetch

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.

27. Fetch with 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.

28. Reusable Fetch Function

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);

29. Common Fetch API Mistakes

  • Forgetting to use await
  • Forgetting response.json()
  • Not checking response.ok
  • Not handling network errors
  • Forgetting JSON.stringify() when sending JSON
  • Using the wrong HTTP method
  • Forgetting the Content-Type header
  • Forgetting the Authorization header for protected APIs
  • Hardcoding API URLs throughout the application
  • Not showing loading feedback

30. Complete Fetch API Example

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.

📌 Key Points

  • Fetch API is used to send HTTP requests from React Native.
  • fetch() returns a Promise.
  • async/await makes asynchronous Fetch code easier to read.
  • Use response.json() to read JSON data.
  • Use response.ok to check whether the HTTP request succeeded.
  • HTTP 404 or 500 does not automatically cause fetch() to throw.
  • Use try/catch for network and processing errors.
  • Use JSON.stringify() when sending JavaScript objects as JSON.
  • Use the Content-Type header when sending JSON.
  • Use the Authorization header for protected APIs.
  • Use React state for API data, loading, and errors.
  • Use useEffect() when data should load when a screen opens.
  • Reusable API functions reduce duplicate code.

🧠 Quick Quiz

Question: Which method is used to convert a Fetch API JSON response into a JavaScript object?