Lesson 99 of 158 – React Native POST Request with Fetch
63%

React Native POST Request with Fetch

A POST request is used when a React Native application needs to send data to a REST API. It is commonly used for registration, login, adding students, creating products, submitting forms, and other operations that create data on the server.

Note: In this lesson, we will learn how to send JSON data from React Native to a PHP REST API using the Fetch API.

1. What is a POST Request?

POST is an HTTP method commonly used to send data to a server.

React Native
     ↓
POST Request
     ↓
PHP REST API
     ↓
Validate Data
     ↓
MySQL
     ↓
JSON Response

2. When Do We Use POST?

POST can be used for operations such as:

  • User registration
  • Student registration
  • Login
  • Adding a student
  • Creating a course
  • Submitting a form
  • Creating a payment record

3. Basic POST Syntax

fetch(API_URL, {
    method: "POST"
});

The request body can be added when the application needs to send data.

4. POST Request with JSON

const response = await fetch(
    API_URL,
    {
        method: "POST",

        headers: {
            "Content-Type": "application/json"
        },

        body: JSON.stringify({
            name: "Rahul",
            email: "rahul@example.com"
        })
    }
);

5. Why Use JSON.stringify()?

JavaScript objects cannot simply be placed into a JSON request body. JSON.stringify() converts the JavaScript object into a JSON string.

const student = {
    name: "Rahul",
    email: "rahul@example.com"
};

const jsonData = JSON.stringify(student);

console.log(jsonData);

6. Content-Type Header

When sending JSON, use the Content-Type header.

headers: {
    "Content-Type": "application/json"
}

This tells the PHP API that the request body contains JSON data.

7. PHP Reading JSON Data

The PHP API can read the JSON request body using php://input.

$input = json_decode(
    file_get_contents("php://input"),
    true
);

$name = $input['name'] ?? '';
$email = $input['email'] ?? '';

8. Sending Student Data

const student = {
    name: "Rahul Kumar",
    email: "rahul@example.com",
    course: "React Native"
};

const response = await fetch(
    "https://example.com/api/students.php",
    {
        method: "POST",

        headers: {
            "Content-Type": "application/json"
        },

        body: JSON.stringify(student)
    }
);

9. Reading the POST Response

const response = await fetch(
    API_URL,
    {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify(student)
    }
);

const result = await response.json();

console.log(result);

10. Standard Success Response

A PHP API can return a standard response after successfully creating a record.

{
    "success": true,
    "message": "Student created successfully",
    "data": {
        "id": 15,
        "name": "Rahul Kumar"
    }
}

React Native can use result.data to access the newly created record.

11. Checking POST Success

const result = await response.json();

if (result.success) {

    console.log(
        "Student created:",
        result.data
    );

} else {

    console.log(
        result.message
    );

}

12. Checking response.ok

const response = await fetch(
    API_URL,
    {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify(student)
    }
);

if (!response.ok) {

    console.log(
        "HTTP Error:",
        response.status
    );
}

const result = await response.json();

13. POST Request with try/catch

async function addStudent() {

    try {

        const response = await fetch(
            API_URL,
            {
                method: "POST",
                headers: {
                    "Content-Type":
                        "application/json"
                },
                body: JSON.stringify({
                    name: "Rahul",
                    email: "rahul@example.com"
                })
            }
        );

        const result =
            await response.json();

        console.log(result);

    } catch (error) {

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

    }
}

14. Sending Form State Data

React Native form values can be collected into an object and sent to the API.

const student = {
    name: name,
    email: email,
    course: course
};

const response = await fetch(
    API_URL,
    {
        method: "POST",

        headers: {
            "Content-Type": "application/json"
        },

        body: JSON.stringify(student)
    }
);

15. Example TextInput Form

const [name, setName] = useState("");
const [email, setEmail] = useState("");

<TextInput
    value={name}
    onChangeText={setName}
    placeholder="Enter name"
/>

<TextInput
    value={email}
    onChangeText={setEmail}
    placeholder="Enter email"
/>

The state values can later be sent using a POST request.

16. POST Form Submission

async function handleSubmit() {

    const response = await fetch(
        API_URL,
        {
            method: "POST",

            headers: {
                "Content-Type":
                    "application/json"
            },

            body: JSON.stringify({
                name,
                email
            })
        }
    );

    const result =
        await response.json();

    console.log(result);
}

17. Server-Side Validation

The PHP API must validate data even if React Native already validates it.

$errors = [];

if ($name === '') {
    $errors['name'] = "Name is required";
}

if (!filter_var(
    $email,
    FILTER_VALIDATE_EMAIL
)) {
    $errors['email'] =
        "Valid email is required";
}

Client-side validation improves user experience, while server-side validation protects the API.

18. Validation Error Response

The PHP API can return HTTP 422 for invalid input.

{
    "success": false,
    "message": "Validation failed",
    "errors": {
        "name": "Name is required",
        "email": "Invalid email address"
    }
}

React Native can display these messages to the user.

19. Handling Validation Errors in React Native

const result = await response.json();

if (!result.success) {

    if (result.errors) {

        console.log(
            result.errors
        );

    }

    console.log(
        result.message
    );
}

20. POST Request with Authentication

Protected POST endpoints can require a JWT token.

const response = await fetch(
    API_URL,
    {
        method: "POST",

        headers: {
            "Content-Type":
                "application/json",

            "Authorization":
                `Bearer ${token}`
        },

        body: JSON.stringify({
            name: "Rahul",
            email: "rahul@example.com"
        })
    }
);

21. POST Request and PHP PDO

After validation, the PHP API can insert the received data using PDO.

$stmt = $pdo->prepare(
    "INSERT INTO students
    (name, email)
    VALUES (?, ?)"
);

$stmt->execute([
    $name,
    $email
]);

$studentId = $pdo->lastInsertId();

Prepared statements help protect against SQL injection.

22. HTTP 201 Created

When a new resource is successfully created, the API can return HTTP 201.

http_response_code(201);

echo json_encode([
    "success" => true,
    "message" => "Student created successfully",
    "data" => [
        "id" => $studentId
    ]
]);

23. Showing Success Message

const result = await response.json();

if (result.success) {

    Alert.alert(
        "Success",
        result.message
    );

}

After successful creation, the application can navigate to another screen or refresh the list.

24. Clearing Form After Success

if (result.success) {

    setName("");
    setEmail("");

    Alert.alert(
        "Success",
        "Student added successfully"
    );
}

Clearing the form after a successful request provides a better user experience.

25. Loading State During POST

const [loading, setLoading] =
    useState(false);

async function handleSubmit() {

    setLoading(true);

    try {

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

        const result =
            await response.json();

        console.log(result);

    } catch (error) {

        console.log(error.message);

    } finally {

        setLoading(false);

    }
}

26. Preventing Duplicate Submission

A loading state can also prevent the user from submitting the same form repeatedly while the request is still running.

async function handleSubmit() {

    if (loading) {
        return;
    }

    setLoading(true);

    try {

        // POST request

    } finally {

        setLoading(false);

    }
}

27. Reusable POST Function

async function createStudent(student) {

    const response = await fetch(
        API_URL,
        {
            method: "POST",

            headers: {
                "Content-Type":
                    "application/json"
            },

            body: JSON.stringify(student)
        }
    );

    const result =
        await response.json();

    if (!response.ok) {

        throw new Error(
            result.message ||
            "Unable to create student"
        );

    }

    return result;
}

28. Complete POST Example

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

async function addStudent() {

    const student = {
        name: "Rahul Kumar",
        email: "rahul@example.com",
        course: "React Native"
    };

    try {

        const response = await fetch(
            API_URL,
            {
                method: "POST",

                headers: {
                    "Content-Type":
                        "application/json",
                    "Accept":
                        "application/json"
                },

                body: JSON.stringify(student)
            }
        );

        const result =
            await response.json();

        if (!response.ok) {

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

        }

        if (result.success) {

            console.log(
                "Created:",
                result.data
            );

        } else {

            console.log(
                result.message
            );

        }

    } catch (error) {

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

    }
}

29. Common POST Request Mistakes

  • Forgetting method: "POST"
  • Forgetting the Content-Type header
  • Forgetting JSON.stringify()
  • Sending invalid or incomplete data
  • Not validating data on the server
  • Not checking response.ok
  • Not handling API errors
  • Not showing a loading state
  • Sending protected requests without authentication
  • Using SQL queries without prepared statements on the server

30. Complete POST Request Flow

React Native Form
        ↓
   Collect Input
        ↓
    Validate
        ↓
     fetch()
        ↓
   POST Request
        ↓
    PHP API
        ↓
Server Validation
        ↓
      PDO
        ↓
      MySQL
        ↓
   JSON Response
        ↓
  React Native
        ↓
 Success / Error
        ↓
     Update UI

This pattern is the foundation for registration forms, student creation, login requests, course creation, and many other mobile application features.

📌 Key Points

  • POST is commonly used to send data to a REST API.
  • Use method: "POST" with fetch().
  • Use Content-Type: application/json when sending JSON.
  • Use JSON.stringify() to convert JavaScript objects into JSON.
  • PHP can read JSON using php://input.
  • Always validate data on the server.
  • Use PDO prepared statements for database operations.
  • HTTP 201 is commonly used after successfully creating a resource.
  • Use JWT authentication for protected POST endpoints.
  • Handle loading, validation, network, and server errors.
  • Clear or update the form after a successful operation.
  • Reusable POST functions make React Native applications easier to maintain.

🧠 Quick Quiz

Question: Which JavaScript method is used to convert a React Native object into JSON before sending it in a POST request?