Lesson 112 of 158 – Axios DELETE Request
71%

Axios DELETE Request

The Axios DELETE method is used to delete an existing resource through a REST API. In a React Native application, Axios can send a DELETE request to a PHP REST API, which can then remove the corresponding record from a MySQL database.

Note: In this lesson, we will learn how to delete records using React Native + Axios + PHP REST API + MySQL.

1. What is a DELETE Request?

A DELETE request is commonly used to remove an existing resource from a server.

React Native
      ↓
 Axios DELETE
      ↓
 PHP REST API
      ↓
   Validate
      ↓
    MySQL
      ↓
 Delete Record
      ↓
 JSON Response

2. DELETE vs Other HTTP Methods

Method Common Purpose
GET Retrieve data
POST Create data
PUT Update data
PATCH Partially update data
DELETE Delete data

3. Basic Axios DELETE Syntax

const response =
    await axios.delete(
        API_URL
    );

The axios.delete() method sends a DELETE request to the server.

4. Deleting a Student

const response =
    await axios.delete(
        `${API_URL}?id=10`
    );

console.log(
    response.data
);

Here, id=10 identifies the student that should be deleted.

5. Using async/await

async function deleteStudent() {

    try {

        const response =
            await axios.delete(
                `${API_URL}?id=10`
            );

        console.log(
            response.data
        );

    } catch (error) {

        console.log(
            error.message
        );

    }
}

6. Sending the Student ID

The API needs to know which record should be deleted. A common approach is to send the ID as a query parameter.

DELETE /api/students.php?id=10

PHP can read this ID from the URL.

7. PHP Reading the ID

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

Validating the ID helps prevent invalid input from reaching the database operation.

8. Validating the ID

if (!$id) {

    http_response_code(400);

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

    exit;
}

9. Checking Whether the Student Exists

Before deleting a record, it is useful to check whether the record exists.

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

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

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

    http_response_code(404);

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

    exit;
}

10. DELETE SQL Statement

SQL uses the DELETE statement to remove a database record.

DELETE FROM students
WHERE id = ?

The ID should be supplied through a prepared statement.

11. Deleting with PDO

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

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

Prepared statements keep the ID separate from the SQL command.

12. Checking rowCount()

If you already checked that the record exists, this additional check can help detect whether the DELETE statement actually affected a row.

13. Successful Delete Response

http_response_code(200);

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

14. HTTP 204 No Content

A DELETE API can also use HTTP 204 No Content when the server successfully deletes the resource and does not need to return a response body.

http_response_code(204);

exit;

If you want to return a JSON message, use a response such as HTTP 200 instead.

15. Axios DELETE Response

const response =
    await axios.delete(
        `${API_URL}?id=${studentId}`
    );

console.log(
    response.data.message
);

When the API returns JSON, Axios makes it available through response.data.

16. Delete Confirmation

Deleting data is usually a destructive action. The application can ask the user for confirmation before sending the DELETE request.

const confirmDelete =
    window.confirm(
        "Delete this student?"
    );

In React Native, a native confirmation dialog such as Alert.alert() can be used instead.

17. React Native Alert Confirmation

import {
    Alert
} from "react-native";

function confirmDelete() {

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

18. Delete Function in React Native

async function deleteStudent(
    studentId
) {

    try {

        const response =
            await axios.delete(
                `${API_URL}?id=${studentId}`
            );

        console.log(
            response.data.message
        );

    } catch (error) {

        console.log(
            error.message
        );
    }
}

19. Loading State During Delete

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

async function deleteStudent(
    studentId
) {

    setDeleting(true);

    try {

        await axios.delete(
            `${API_URL}?id=${studentId}`
        );

    } catch (error) {

        console.log(
            error.message
        );

    } finally {

        setDeleting(false);
    }
}

20. Removing the Deleted Item from State

After a successful DELETE request, the application can remove the deleted item from the local list.

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

This updates the screen without requiring a complete reload.

21. Handling HTTP 404

If the requested record does not exist, the API can return HTTP 404 Not Found.

try {

    await axios.delete(
        `${API_URL}?id=${studentId}`
    );

} catch (error) {

    if (
        error.response?.status === 404
    ) {

        console.log(
            "Student not found"
        );
    }
}

22. Handling Other Axios Errors

try {

    await axios.delete(
        `${API_URL}?id=${studentId}`
    );

} catch (error) {

    if (error.response) {

        console.log(
            error.response.status
        );

        console.log(
            error.response.data
        );

    } else {

        console.log(
            "Network error"
        );
    }
}

23. DELETE with JWT Authentication

A protected DELETE endpoint should authenticate the user and verify that the user has permission to delete the resource.

const response =
    await axios.delete(

        `${API_URL}?id=${studentId}`,

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

24. Authorization Before Delete

Authentication answers: "Who is the user?"

Authorization answers: "Is this user allowed to delete this record?"

The PHP API should perform this check on the server. Hiding the delete button in React Native is not enough for security.

if ($userRole !== 'admin') {

    http_response_code(403);

    echo json_encode([
        "success" => false,
        "message" =>
            "Access denied"
    ]);

    exit;
}

25. Complete PHP DELETE API

<?php

header(
    "Content-Type: application/json"
);

require_once "../db.php";

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

if (!$id) {

    http_response_code(400);

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

    exit;
}

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

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

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

    http_response_code(404);

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

    exit;
}

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

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

if ($stmt->rowCount() === 0) {

    http_response_code(404);

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

    exit;
}

http_response_code(200);

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

26. Complete React Native Delete Function

async function deleteStudent(
    studentId
) {

    setDeleting(true);
    setMessage("");

    try {

        const response =
            await axios.delete(
                `${API_URL}?id=${studentId}`
            );

        if (
            response.status === 200
        ) {

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

            setMessage(
                response.data.message
            );
        }

    } catch (error) {

        if (error.response) {

            setMessage(
                error.response.data?.message ||
                "Unable to delete student"
            );

        } else {

            setMessage(
                "Network error"
            );
        }

    } finally {

        setDeleting(false);
    }
}

27. Delete Button in a Student List

<FlatList

    data={students}

    keyExtractor={item =>
        item.id.toString()
    }

    renderItem={({ item }) => (

        <View>

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

            <Button
                title="Delete"
                onPress={() =>
                    confirmDelete(
                        item.id
                    )
                }
            />

        </View>

    )}
/>

The delete action should normally be confirmed before the request is sent.

28. Complete React Native Delete Example

import React, {
    useState
} from "react";

import {
    View,
    Text,
    Button,
    FlatList,
    Alert,
    ActivityIndicator
} from "react-native";

import axios from "axios";

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

export default function StudentList() {

    const [students, setStudents] =
        useState([]);

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

    const [message, setMessage] =
        useState("");

    function confirmDelete(
        studentId
    ) {

        Alert.alert(
            "Delete Student",
            "Are you sure you want to delete this student?",

            [
                {
                    text: "Cancel",
                    style: "cancel"
                },

                {
                    text: "Delete",

                    onPress: () =>
                        deleteStudent(
                            studentId
                        )
                }
            ]
        );
    }

    async function deleteStudent(
        studentId
    ) {

        setDeleting(true);
        setMessage("");

        try {

            const response =
                await axios.delete(
                    `${API_URL}?id=${studentId}`
                );

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

            setMessage(
                response.data.message
            );

        } catch (error) {

            if (error.response) {

                setMessage(
                    error.response.data?.message ||
                    "Unable to delete student"
                );

            } else {

                setMessage(
                    "Network error"
                );
            }

        } finally {

            setDeleting(false);
        }
    }

    return (

        <View style={{
            flex: 1,
            padding: 20
        }}>

            {deleting && (
                <ActivityIndicator
                    size="small"
                />
            )}

            <Text>
                {message}
            </Text>

            <FlatList

                data={students}

                keyExtractor={item =>
                    item.id.toString()
                }

                renderItem={({ item }) => (

                    <View style={{
                        padding: 15
                    }}>

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

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

                        <Text>
                            Course:
                            {item.course}
                        </Text>

                        <Button
                            title="Delete"
                            onPress={() =>
                                confirmDelete(
                                    item.id
                                )
                            }
                        />

                    </View>

                )}

                ListEmptyComponent={
                    <Text>
                        No students found.
                    </Text>
                }

            />

        </View>
    );
}

29. Common Axios DELETE Mistakes

  • Using the wrong HTTP method.
  • Forgetting the record ID.
  • Using an incorrect API URL.
  • Not checking whether the record exists.
  • Building SQL using string concatenation.
  • Not using prepared statements.
  • Deleting data without authorization checks.
  • Not confirming destructive actions.
  • Not handling 404 errors.
  • Not handling network errors.
  • Not updating the React Native list after deletion.

30. Complete Axios DELETE Flow

React Native
      ↓
Delete Button
      ↓
Confirmation
      ↓
axios.delete()
      ↓
DELETE /students.php?id=10
      ↓
PHP REST API
      ↓
Authentication
      ↓
Authorization
      ↓
Validate ID
      ↓
Check Record
      ↓
Prepared DELETE
      ↓
MySQL
      ↓
JSON Response
      ↓
Update React Native State
      ↓
Remove Item from UI

DELETE requests should always be handled carefully because they can remove important data permanently.

📌 Key Points

  • axios.delete() is used to send DELETE requests.
  • DELETE is commonly used to remove an existing resource.
  • The record ID identifies which resource should be deleted.
  • PHP can read the ID using $_GET or filter_input().
  • Check whether the record exists before deleting it.
  • Use PDO prepared statements for DELETE queries.
  • HTTP 200 can return a JSON success response.
  • HTTP 204 can be used when no response body is required.
  • HTTP 404 can indicate that the record does not exist.
  • Protected DELETE endpoints should verify authentication and authorization.
  • Use a confirmation dialog before destructive actions.
  • Update React Native state after a successful deletion.

🧠 Quick Quiz

Question: Which Axios method is used to send a DELETE request?