Lesson 101 of 158 – React Native DELETE Request with Fetch
64%

React Native DELETE Request with Fetch

A DELETE request is used to remove an existing resource from a REST API. In a React Native application, Fetch can send a DELETE request to a PHP REST API, which can then validate the request and delete the corresponding record from the MySQL database.

Note: In this lesson, we will learn how to delete records using the DELETE method, React Native Fetch, PHP REST API, PDO, and MySQL.

1. What is a DELETE Request?

DELETE is an HTTP method commonly used to remove an existing resource.

React Native
     ↓
DELETE Request
     ↓
PHP REST API
     ↓
Authentication
     ↓
Authorization
     ↓
MySQL DELETE
     ↓
JSON Response

2. When Do We Use DELETE?

DELETE can be used for operations such as:

  • Deleting a student
  • Deleting a user
  • Deleting a course
  • Deleting a product
  • Deleting an assignment
  • Deleting an unwanted record

3. Basic DELETE Syntax

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

The API must know which resource should be deleted.

4. DELETE Request with an ID

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

DELETE /api/students.php?id=10

Here, 10 identifies the student that should be deleted.

5. React Native DELETE Request

const studentId = 10;

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

6. DELETE Request with Headers

Headers can be used when the API requires authentication or other request information.

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

        headers: {
            "Accept": "application/json"
        }
    }
);

7. Reading the DELETE Response

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

const result =
    await response.json();

console.log(result);

8. Standard DELETE Success Response

The PHP API can return a JSON response after successful deletion.

{
    "success": true,
    "message": "Student deleted successfully"
}

9. Checking DELETE Success

const result =
    await response.json();

if (result.success) {

    console.log(
        result.message
    );

} else {

    console.log(
        result.message
    );

}

10. Checking response.ok

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

if (!response.ok) {

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

const result =
    await response.json();

11. DELETE with try/catch

async function deleteStudent() {

    try {

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

        const result =
            await response.json();

        console.log(result);

    } catch (error) {

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

    }
}

12. PHP Reading the Student ID

PHP can read the ID from the query string and validate it.

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

13. Checking Whether the Record Exists

14. PHP DELETE Query

Use a PDO prepared statement to delete the record.

$stmt = $pdo->prepare(
    "DELETE FROM students
     WHERE id = ?"
);

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

Prepared statements help protect the database from SQL injection.

15. Checking rowCount()

If the record was already checked before DELETE, this can be used to confirm that the DELETE operation actually removed a row.

16. HTTP 200 After DELETE

An API can return HTTP 200 with a JSON message after a successful delete.

http_response_code(200);

echo json_encode([
    "success" => true,
    "message" =>
        "Student deleted successfully"
]);

17. HTTP 204 No Content

Another valid approach is HTTP 204 No Content when the server does not return a response body.

http_response_code(204);

If the API returns 204, React Native should not attempt to parse an empty response body with response.json().

18. DELETE with JWT Authentication

Sensitive DELETE operations should normally be protected.

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

        headers: {
            "Accept":
                "application/json",

            "Authorization":
                `Bearer ${token}`
        }
    }
);

19. Authentication vs Authorization

Authentication verifies who the user is. Authorization determines whether that user has permission to delete the resource.

JWT Token
    ↓
Verify User
    ↓
Check Role / Permission
    ↓
Check Resource Ownership
    ↓
DELETE Record

20. React Native Delete Button

<Button
    title="Delete Student"
    onPress={() =>
        deleteStudent(student.id)
    }
/>

The selected student's ID can be passed to the delete function.

21. Delete Function

async function deleteStudent(
    studentId
) {

    try {

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

        const result =
            await response.json();

        if (result.success) {

            console.log(
                "Deleted successfully"
            );

        }

    } catch (error) {

        console.log(
            error.message
        );

    }
}

22. Confirm Before Delete

Deleting data is often irreversible, so the application should ask the user for confirmation.

Alert.alert(
    "Delete Student",
    "Are you sure you want to delete this student?",
    [
        {
            text: "Cancel"
        },
        {
            text: "Delete",
            onPress: () =>
                deleteStudent(student.id)
        }
    ]
);

23. Removing Deleted Data from the UI

After a successful DELETE request, the deleted item should also be removed from the React Native state.

setStudents(
    students.filter(
        student =>
            student.id !== studentId
    )
);

This allows the screen to update without loading the complete list again.

24. Handling 404 Response

HTTP 404 means the requested resource could not be found.

if (response.status === 404) {

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

    return;
}

25. Handling 401 and 403

A protected DELETE endpoint may return different authentication and authorization errors.

if (response.status === 401) {

    console.log(
        "Please login again."
    );

}

if (response.status === 403) {

    console.log(
        "You do not have permission."
    );

}

26. Loading State During Delete

const [deleting, setDeleting] =
    useState(false);

async function deleteStudent(
    studentId
) {

    if (deleting) {
        return;
    }

    setDeleting(true);

    try {

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

        const result =
            await response.json();

        console.log(result);

    } catch (error) {

        console.log(
            error.message
        );

    } finally {

        setDeleting(false);

    }
}

27. Reusable DELETE Function

async function deleteRecord(
    id
) {

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

            headers: {
                "Accept":
                    "application/json"
            }
        }
    );

    const result =
        await response.json();

    if (!response.ok) {

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

    }

    return result;
}

28. Complete DELETE Example

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

async function deleteStudent(
    studentId
) {

    try {

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

                headers: {
                    "Accept":
                        "application/json",
                    "Authorization":
                        `Bearer ${token}`
                }
            }
        );

        if (response.status === 204) {

            console.log(
                "Deleted successfully"
            );

            return;

        }

        const result =
            await response.json();

        if (!response.ok) {

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

        }

        if (result.success) {

            console.log(
                result.message
            );

            setStudents(
                students.filter(
                    student =>
                        student.id !== studentId
                )
            );

        }

    } catch (error) {

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

    }
}

29. Common DELETE Request Mistakes

  • Forgetting method: "DELETE"
  • Not sending the record ID
  • Not checking whether the record exists
  • Not checking authentication
  • Not checking authorization
  • Deleting another user's data without permission checks
  • Not using prepared statements
  • Not handling 404 responses
  • Not handling 401 and 403 responses
  • Trying to parse JSON from a 204 response
  • Not confirming destructive actions in the UI
  • Not updating the React Native list after deletion

30. Complete DELETE Request Flow

React Native Student List
          ↓
     Press Delete
          ↓
    Confirm Action
          ↓
       fetch()
          ↓
    DELETE Request
          ↓
      PHP API
          ↓
   Authenticate User
          ↓
   Authorize Action
          ↓
      Validate ID
          ↓
    Check Record
          ↓
      PDO DELETE
          ↓
       MySQL
          ↓
    JSON Response
          ↓
     React Native
          ↓
    Update UI List

This is the basic pattern for safely deleting resources from a React Native application through a PHP and MySQL REST API.

📌 Key Points

  • DELETE is commonly used to remove an existing resource.
  • Use method: "DELETE" with Fetch.
  • Send the resource ID so the API knows what to delete.
  • Validate the ID on the PHP server.
  • Check whether the record exists before deleting when needed.
  • Use PDO prepared statements for DELETE queries.
  • Protected DELETE endpoints should use authentication and authorization.
  • HTTP 404 can indicate that the resource does not exist.
  • HTTP 401 indicates an authentication problem.
  • HTTP 403 indicates that the user does not have permission.
  • HTTP 204 can be used when the server returns no response body.
  • Confirm destructive actions before deleting data.
  • Update React Native state after a successful deletion.

🧠 Quick Quiz

Question: Which HTTP method is commonly used to delete an existing resource?