Lesson 51 of 60 – Fetch API in React Native
85%

Fetch API in React Native

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
Note: Fetch API is a JavaScript API for making network requests. React Native applications commonly use it to communicate with REST APIs.

1. What is Fetch API?

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.

2. Why Use Fetch API?

Mobile applications often need data from a remote server.

  • Get user information
  • Load courses
  • Fetch products
  • Submit forms
  • Send login requests
  • Update server data

Fetch API can be used for these HTTP operations.

3. Basic Fetch Syntax

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.

4. Fetch API and Promises

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.

5. Using async and await

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.

6. Creating a Fetch Function

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;

}

7. Using Fetch with useEffect

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.

8. Storing API Data with useState

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.

9. Complete GET Request

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.

10. Checking the Response

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.

11. Converting Response to JSON

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.

12. Displaying API Data

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>

13. Loading State

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

14. Displaying ActivityIndicator

The ActivityIndicator component can be displayed while data is loading.

{loading ? (

    <ActivityIndicator />

) : (

    <Text>
        Data Loaded
    </Text>

)}

15. Handling Fetch Errors

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

}

16. Creating an Error State

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

}

17. Complete GET Request with Loading and Error

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.

18. Sending a POST Request

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

});

19. POST Request with async and await

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

}

20. Sending Headers

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.

21. Using Fetch for Login

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.

22. Fetching Course Data

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

}

23. Fetch with FlatList

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.

24. Refreshing 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.

25. API URL Management

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.

26. Common Fetch API Mistakes

  • Forgetting to call response.json() when JSON is expected.
  • Not checking response.ok.
  • Ignoring network errors.
  • Not displaying a loading state.
  • Not displaying an error state.
  • Sending incorrect request headers.
  • Using the wrong HTTP method.
  • Repeating API URLs throughout the application.
  • Putting too much network logic directly inside UI code.

27. Complete Fetch API Example

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.

28. Fetch API Best Practices

  • Keep API functions organized.
  • Use async and await where it improves readability.
  • Always handle possible network errors.
  • Check HTTP response status before using response data.
  • Show loading feedback during network requests.
  • Show useful error messages to users.
  • Keep API URLs organized.
  • Do not expose sensitive credentials in application source code.
  • Use secure HTTPS endpoints for production APIs.

29. Important Fetch API Concepts

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

30. Complete Fetch API Workflow

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.

📌 Key Points

  • Fetch API is used to communicate with web APIs.
  • fetch() returns a Promise.
  • Use response.json() to parse JSON responses.
  • Use async and await for readable asynchronous code.
  • Check response.ok before processing important responses.
  • Use GET requests to retrieve data.
  • Use POST requests to send data.
  • Use useState to store API data.
  • Use useEffect to load data when a screen starts.
  • Always handle loading and error states.
  • FlatList is useful for displaying API lists.
  • Keep API logic organized as applications become larger.

🧠 Quick Quiz

Question: Which function is commonly used in React Native to make a network request?