Lesson 100 of 158 – React Native PUT Request with Fetch
63%

React Native PUT Request with Fetch

A PUT request is commonly used to update an existing resource in a REST API. In a React Native application, Fetch can send updated data to a PHP REST API, which can then validate the data and update the MySQL database.

Note: In this lesson, we will learn how to update existing records using the PUT method, Fetch API, PHP REST API, and MySQL.

1. What is a PUT Request?

PUT is an HTTP method commonly used to update an existing resource.

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

2. When Do We Use PUT?

PUT can be used for operations such as:

  • Updating student information
  • Updating user profiles
  • Updating course information
  • Updating product information
  • Updating employee records
  • Updating account information

3. Basic PUT Syntax

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

The request body can contain the new values that should replace or update the existing resource.

4. PUT Request with JSON

const response = await fetch(
    `${API_URL}?id=10`,
    {
        method: "PUT",

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

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

5. Why Use JSON.stringify()?

React Native uses JavaScript objects, while the API expects JSON data. JSON.stringify() converts the object into JSON text.

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

const jsonData =
    JSON.stringify(student);

6. Content-Type Header

When sending JSON data, specify the Content-Type header.

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

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

7. Identifying the Resource

The API needs to know which record should be updated.

A common approach is to send the record ID as a query parameter.

PUT /api/students.php?id=10

Here, 10 identifies the student that should be updated.

8. React Native PUT Request

const studentId = 10;

const response = await fetch(
    `${API_URL}?id=${studentId}`,
    {
        method: "PUT",

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

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

9. Reading the PUT Response

const response = await fetch(
    `${API_URL}?id=10`,
    {
        method: "PUT",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify({
            name: "Rahul Kumar",
            email: "rahulkumar@example.com"
        })
    }
);

const result = await response.json();

console.log(result);

10. Standard Success Response

After a successful update, the PHP API can return:

{
    "success": true,
    "message": "Student updated successfully",
    "data": {
        "id": 10,
        "name": "Rahul Kumar",
        "email": "rahulkumar@example.com"
    }
}

11. Checking PUT Success

const result = await response.json();

if (result.success) {

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

} else {

    console.log(
        result.message
    );

}

12. Checking response.ok

const response = await fetch(
    `${API_URL}?id=10`,
    {
        method: "PUT",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify({
            name: "Rahul Kumar"
        })
    }
);

if (!response.ok) {

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

const result = await response.json();

13. PUT with try/catch

async function updateStudent() {

    try {

        const response = await fetch(
            `${API_URL}?id=10`,
            {
                method: "PUT",

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

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

        const result =
            await response.json();

        console.log(result);

    } catch (error) {

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

    }
}

14. PHP Reading PUT Data

PHP can read JSON data from the request body.

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

$name = trim($input['name'] ?? '');
$email = trim($input['email'] ?? '');

15. PHP Reading the Student ID

$studentId = filter_input(
    INPUT_GET,
    'id',
    FILTER_VALIDATE_INT
);

if (!$studentId) {

    http_response_code(400);

    echo json_encode([
        "success" => false,
        "message" => "Valid student ID is required"
    ]);

    exit;
}

16. PHP Validation Before Update

$errors = [];

if ($name === '') {

    $errors['name'] =
        "Name is required";
}

if (!filter_var(
    $email,
    FILTER_VALIDATE_EMAIL
)) {

    $errors['email'] =
        "Valid email is required";
}

if (!empty($errors)) {

    http_response_code(422);

    echo json_encode([
        "success" => false,
        "message" => "Validation failed",
        "errors" => $errors
    ]);

    exit;
}

17. PHP UPDATE Query

PDO prepared statements should be used for the database update.

$stmt = $pdo->prepare(
    "UPDATE students
     SET name = ?, email = ?
     WHERE id = ?"
);

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

18. Checking rowCount()

rowCount() should not be treated as a universal way to distinguish "not found" from "no values changed" for every database setup. If that distinction matters, first check whether the record exists.

19. Checking Whether the Student Exists

$check = $pdo->prepare(
    "SELECT id
     FROM students
     WHERE id = ?"
);

$check->execute([
    $studentId
]);

if (!$check->fetch()) {

    http_response_code(404);

    echo json_encode([
        "success" => false,
        "message" => "Student not found"
    ]);

    exit;
}

20. PUT with JWT Authentication

Protected update endpoints should verify the user's authentication token.

const response = await fetch(
    `${API_URL}?id=${studentId}`,
    {
        method: "PUT",

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

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

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

21. Authorization Before Update

Authentication alone does not necessarily mean the user is allowed to update every student.

JWT Verification
       ↓
Identify User
       ↓
Check Role / Permission
       ↓
Check Resource Ownership
       ↓
Update Student

The server should enforce these rules.

22. Updating a React Native Form

Existing student information can first be loaded into state.

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

setName(student.name);
setEmail(student.email);

After editing the fields, the updated values can be sent using PUT.

23. PUT Form Submission

async function handleUpdate() {

    const response = await fetch(
        `${API_URL}?id=${studentId}`,
        {
            method: "PUT",

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

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

    const result =
        await response.json();

    if (result.success) {

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

    } else {

        Alert.alert(
            "Error",
            result.message
        );
    }
}

24. Loading State During Update

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

async function handleUpdate() {

    if (loading) {
        return;
    }

    setLoading(true);

    try {

        // PUT request

    } catch (error) {

        console.log(error.message);

    } finally {

        setLoading(false);

    }
}

The loading state can prevent accidental repeated submissions.

25. Handling 404 Response

The API may return 404 if the requested student does not exist.

if (response.status === 404) {

    Alert.alert(
        "Not Found",
        "Student does not exist."
    );

    return;
}

26. Handling Validation Errors

A PHP API can return HTTP 422 when submitted values are invalid.

if (response.status === 422) {

    const result =
        await response.json();

    console.log(
        result.errors
    );

    return;
}

The application can use these field-specific errors to show messages beside the form fields.

27. Reusable PUT Function

async function updateStudent(
    studentId,
    student
) {

    const response = await fetch(
        `${API_URL}?id=${studentId}`,
        {
            method: "PUT",

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

            body: JSON.stringify(student)
        }
    );

    const result =
        await response.json();

    if (!response.ok) {

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

    }

    return result;
}

28. Complete PUT Example

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

async function updateStudent() {

    const studentId = 10;

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

    try {

        const response = await fetch(
            `${API_URL}?id=${studentId}`,
            {
                method: "PUT",

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

        }

        if (result.success) {

            console.log(
                "Updated successfully:",
                result.data
            );

        } else {

            console.log(
                result.message
            );

        }

    } catch (error) {

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

    }
}

29. Common PUT Request Mistakes

  • Forgetting method: "PUT"
  • Forgetting JSON.stringify()
  • Forgetting the Content-Type header
  • Not sending the record ID
  • Not checking whether the record exists
  • Not validating updated data
  • Not using prepared statements on the PHP side
  • Not checking response.ok
  • Not handling 404 and 422 responses
  • Not checking authentication and authorization
  • Allowing unauthorized users to update another user's data

30. Complete PUT Request Flow

React Native Edit Screen
          ↓
     Load Existing Data
          ↓
       Edit Form
          ↓
      Validate Input
          ↓
        fetch()
          ↓
     PUT Request
          ↓
      PHP REST API
          ↓
 Authentication
          ↓
   Authorization
          ↓
     Validation
          ↓
       PDO UPDATE
          ↓
        MySQL
          ↓
    JSON Response
          ↓
     React Native
          ↓
     Update Screen

This pattern can be used for student profiles, user accounts, courses, products, employee records, and other resources that need to be updated from a React Native application.

📌 Key Points

  • PUT is commonly used to update an existing resource.
  • Use method: "PUT" with Fetch.
  • Send JSON using JSON.stringify().
  • Use the Content-Type header for JSON requests.
  • Identify the resource using an ID or another supported identifier.
  • Validate updated data on the PHP server.
  • Check whether the resource exists before updating when needed.
  • Use PDO prepared statements for SQL UPDATE operations.
  • Protected update APIs should verify authentication and authorization.
  • Handle 404, 422, 401, 403, and other relevant responses.
  • Use loading states to prevent repeated submissions.
  • Keep reusable PUT functions in an API service layer.

🧠 Quick Quiz

Question: Which HTTP method is commonly used to update an existing resource in a REST API?