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.
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
| Method | Common Purpose |
|---|---|
| GET | Retrieve data |
| POST | Create data |
| PUT | Update data |
| PATCH | Partially update data |
| DELETE | Delete data |
const response =
await axios.delete(
API_URL
);
The axios.delete() method sends a DELETE request to the server.
const response =
await axios.delete(
`${API_URL}?id=10`
);
console.log(
response.data
);
Here, id=10 identifies the student that should be deleted.
async function deleteStudent() {
try {
const response =
await axios.delete(
`${API_URL}?id=10`
);
console.log(
response.data
);
} catch (error) {
console.log(
error.message
);
}
}
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.
$id = filter_input(
INPUT_GET,
'id',
FILTER_VALIDATE_INT
);
Validating the ID helps prevent invalid input from reaching the database operation.
if (!$id) {
http_response_code(400);
echo json_encode([
"success" => false,
"message" =>
"Valid student ID is required"
]);
exit;
}
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;
}
SQL uses the DELETE statement to remove a database record.
DELETE FROM students
WHERE id = ?
The ID should be supplied through a prepared statement.
$stmt = $pdo->prepare(
"DELETE FROM students
WHERE id = ?"
);
$stmt->execute([
$id
]);
Prepared statements keep the ID separate from the SQL command.
If you already checked that the record exists, this additional check can help detect whether the DELETE statement actually affected a row.
http_response_code(200);
echo json_encode([
"success" => true,
"message" =>
"Student deleted successfully"
]);
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.
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.
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.
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
}
]
);
}
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
);
}
}
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);
}
}
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.
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"
);
}
}
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"
);
}
}
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}`
}
}
);
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;
}
<?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
]
]);
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);
}
}
<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.
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>
);
}
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.
Question: Which Axios method is used to send a DELETE request?