Lesson 98 of 158 – React Native GET Request with Fetch
62%

React Native GET Request with Fetch

A GET request is used to retrieve data from a REST API. In React Native, the Fetch API can be used to send a GET request to a PHP/MySQL backend and receive JSON data.

Note: In this lesson, we will focus specifically on retrieving data using GET requests and displaying the returned API data in a React Native application.

1. What is a GET Request?

GET is an HTTP method used to retrieve information from a server.

React Native
     ↓
GET Request
     ↓
PHP REST API
     ↓
MySQL
     ↓
JSON Response

GET requests normally do not modify the server's data.

2. Basic GET Request

The simplest GET request uses fetch() with the API URL.

const response = await fetch(
    "https://example.com/api/students.php"
);

Since GET is the default fetch method, the method does not have to be specified.

3. GET Request with Explicit Method

const response = await fetch(
    "https://example.com/api/students.php",
    {
        method: "GET"
    }
);

Writing the method explicitly can make the code easier to understand.

4. Reading the JSON Response

After receiving the response, use response.json() to read the JSON data.

const response = await fetch(API_URL);

const result = await response.json();

console.log(result);

5. Example PHP API Response

Suppose the PHP API returns:

{
    "success": true,
    "message": "Students retrieved successfully",
    "data": [
        {
            "id": 1,
            "name": "Rahul",
            "email": "rahul@example.com"
        },
        {
            "id": 2,
            "name": "Amit",
            "email": "amit@example.com"
        }
    ]
}

6. Accessing API Data

const response = await fetch(API_URL);

const result = await response.json();

console.log(result.data);

The data property contains the records returned by the API.

7. Storing GET Data in State

API data can be stored in React 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);
    }
}

8. Loading Data with useEffect()

useEffect() can be used to load data when the screen is opened.

useEffect(() => {

    loadStudents();

}, []);

The empty dependency array means the effect runs after the initial render.

9. Complete Basic GET Function

async function loadStudents() {

    const response = await fetch(
        "https://example.com/api/students.php"
    );

    const result = await response.json();

    if (result.success) {

        setStudents(result.data);

    }

}

10. Checking response.ok

response.ok can be used to determine whether the HTTP status represents a successful response.

const response = await fetch(API_URL);

if (!response.ok) {

    throw new Error(
        `HTTP Error: ${response.status}`
    );
}

const result = await response.json();

11. Checking HTTP Status Code

const response = await fetch(API_URL);

if (response.status === 200) {

    const result = await response.json();

    console.log(result);

}

HTTP 200 commonly indicates that the GET request was successful.

12. GET Request with try/catch

async function loadStudents() {

    try {

        const response = await fetch(API_URL);

        const result = await response.json();

        if (result.success) {
            setStudents(result.data);
        }

    } catch (error) {

        console.log(
            "Error:",
            error.message
        );

    }

}

13. Handling API Error Messages

A standard API can return an error message.

{
    "success": false,
    "message": "Unable to retrieve students",
    "data": null
}

React Native can read the message:

if (!result.success) {

    console.log(result.message);

}

14. GET Request with Headers

const response = await fetch(
    API_URL,
    {
        method: "GET",
        headers: {
            "Accept": "application/json"
        }
    }
);

The Accept header tells the server which response format the client expects.

15. GET Request with JWT

Protected APIs can require a JWT token.

const response = await fetch(
    API_URL,
    {
        method: "GET",
        headers: {
            "Accept": "application/json",
            "Authorization": `Bearer ${token}`
        }
    }
);

The PHP API should verify the token before returning protected data.

16. GET Request with Query Parameter

Query parameters can be added to the URL.

const response = await fetch(
    `${API_URL}?course=React%20Native`
);

const result = await response.json();

Query parameters are useful for filtering API results.

17. Search Using GET

const search = "Rahul";

const response = await fetch(
    `${API_URL}?search=${encodeURIComponent(search)}`
);

const result = await response.json();

if (result.success) {
    setStudents(result.data);
}

encodeURIComponent() helps safely encode user-entered search text.

18. Multiple Query Parameters

const page = 1;
const limit = 10;
const search = "Rahul";

const url =
    `${API_URL}?page=${page}` +
    `&limit=${limit}` +
    `&search=${encodeURIComponent(search)}`;

const response = await fetch(url);

const result = await response.json();

19. GET Request with URLSearchParams

URLSearchParams can make query parameter construction easier.

const params = new URLSearchParams({
    page: "1",
    limit: "10",
    search: "Rahul"
});

const response = await fetch(
    `${API_URL}?${params.toString()}`
);

const result = await response.json();

20. GET Request with Pagination

const page = 2;
const limit = 10;

const response = await fetch(
    `${API_URL}?page=${page}&limit=${limit}`
);

const result = await response.json();

console.log(result.data);

Pagination allows the mobile application to retrieve only a portion of a large dataset.

21. GET Request with Sorting

const response = await fetch(
    `${API_URL}?sort=name&order=asc`
);

const result = await response.json();

if (result.success) {
    setStudents(result.data);
}

The PHP API should validate allowed sorting columns and directions.

22. GET Request with Filtering

const response = await fetch(
    `${API_URL}?status=active`
);

const result = await response.json();

console.log(result.data);

Filtering lets the API return only records matching a condition.

23. Displaying GET Data with FlatList

<FlatList
    data={students}
    keyExtractor={(item) =>
        item.id.toString()
    }
    renderItem={({ item }) => (
        <View>

            <Text>
                {item.name}
            </Text>

            <Text>
                {item.email}
            </Text>

        </View>
    )}
/>

24. Loading Indicator

Show an ActivityIndicator while the GET request is running.

{loading ? (
    <ActivityIndicator
        size="large"
    />
) : (
    <FlatList
        data={students}
        renderItem={renderStudent}
    />
)}

25. Empty API Result

The API may return an empty array when no records are found.

{
    "success": true,
    "message": "No students found",
    "data": []
}

React Native can display a friendly message when the array is empty.

if (students.length === 0) {

    console.log("No students found");

}

26. Reusable GET Function

async function getStudents() {

    try {

        const response = await fetch(
            API_URL
        );

        const result = await response.json();

        if (!response.ok) {

            throw new Error(
                result.message ||
                "Unable to load students"
            );

        }

        return result;

    } catch (error) {

        throw error;

    }
}

Reusable functions keep API code separate from screen components.

27. Calling the Reusable Function

async function loadStudents() {

    try {

        const result =
            await getStudents();

        if (result.success) {

            setStudents(result.data);

        }

    } catch (error) {

        setError(error.message);

    }
}

28. Complete GET Request Example

const API_URL =
    "https://example.com/api/students.php";

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,
            {
                method: "GET",
                headers: {
                    "Accept": "application/json"
                }
            }
        );

        const result = await response.json();

        if (!response.ok) {

            throw new Error(
                result.message ||
                "Request failed"
            );

        }

        if (result.success) {

            setStudents(result.data);

        } else {

            setError(result.message);

        }

    } catch (error) {

        setError(error.message);

    } finally {

        setLoading(false);

    }
}

useEffect(() => {

    loadStudents();

}, []);

29. Common GET Request Mistakes

  • Using an incorrect API URL
  • Forgetting to call response.json()
  • Not checking response.ok
  • Not handling network errors
  • Not displaying a loading state
  • Not handling an empty result
  • Not encoding search parameters
  • Sending sensitive information through query parameters
  • Not sending the Authorization header for protected APIs
  • Not validating query parameters on the server

30. Complete GET Request Flow

React Native Screen
        ↓
     loadStudents()
        ↓
       fetch()
        ↓
   GET /students.php
        ↓
    PHP REST API
        ↓
      MySQL
        ↓
    JSON Response
        ↓
  response.json()
        ↓
   setStudents()
        ↓
     FlatList
        ↓
   Mobile Screen

GET requests are the foundation for retrieving data from REST APIs. The same pattern can later be extended with authentication, searching, filtering, sorting, pagination, and other API features.

📌 Key Points

  • GET is used to retrieve data from a REST API.
  • fetch() can send GET requests from React Native.
  • GET is the default fetch method.
  • Use response.json() to read JSON data.
  • Check response.ok or response.status before processing the result.
  • Use try/catch to handle network errors.
  • Store API data in React state.
  • useEffect() can load data when a screen opens.
  • Query parameters can be used for search, filtering, sorting, and pagination.
  • Use Authorization headers when the API is protected.
  • FlatList is useful for displaying API lists.
  • Always handle loading, error, and empty-data states.

🧠 Quick Quiz

Question: Which HTTP method is normally used to retrieve data from a REST API?