Lesson 155 of 158 – Project Delete Student Screen
98%

Project Delete Student Screen

In this lesson, we will create the Delete Student functionality for our Student Management mobile application using React Native, TypeScript, Axios, and the PHP REST API.

The user will select a student, confirm the deletion, and the application will send a DELETE request to the protected PHP API. After successful deletion, the student will be removed from the local student list.

Project Goal: Create a secure Delete Student screen and connect it with the protected PHP/MySQL REST API.

1. Delete Student Flow

Student List
      ↓
Select Delete
      ↓
Confirmation
      ↓
DELETE Request
      ↓
JWT Authentication
      ↓
PHP REST API
      ↓
Validate Student ID
      ↓
Check Student
      ↓
MySQL DELETE
      ↓
JSON Response
      ↓
Remove Student from List

2. Why Use DELETE?

The HTTP DELETE method is designed to remove an existing resource.

DELETE /api/students.php?id=5

Here, 5 identifies the student that should be deleted.

3. Delete Response Interface

interface DeleteStudentResponse {
    success: boolean;
    message: string;
}

TypeScript can use this interface to understand the API response.

4. Student Interface

interface Student {
    id: number;
    name: string;
    email: string;
    mobile: string;
    course: string;
    address: string;
}

The Student interface represents the record that will be removed.

5. Import React Native Components

import React, {
    useState
} from "react";

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

6. Delete State

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

const [error, setError] =
    useState("");

const [success, setSuccess] =
    useState("");

The deleting state helps track the DELETE request.

7. Receive Student ID

If a separate Delete screen is used, the selected student ID can be received through React Navigation.

const { id } = route.params;

Example:

{
    id: 5
}

8. DELETE API Endpoint

DELETE /api/students.php?id=5

The ID is supplied as a query parameter.

9. Axios DELETE Request

const response =
    await api.delete<DeleteStudentResponse>(
        "/students.php",
        {
            params: {
                id
            }
        }
    );

Axios sends the DELETE request to the PHP REST API.

10. Why Use Confirmation?

Deleting a student can be a destructive operation. The application should ask the user for confirmation before sending the request.

Are you sure you want
to delete this student?

This helps prevent accidental deletion.

11. React Native Alert

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

The Delete action calls the API only after the user confirms.

12. Delete Function

const deleteStudent =
    async () => {

    try {

        setDeleting(true);
        setError("");
        setSuccess("");

        const response =
            await api.delete<DeleteStudentResponse>(
                "/students.php",
                {
                    params: {
                        id
                    }
                }
            );

        setSuccess(
            response.data.message
        );

    } catch (error) {

        setError(
            "Unable to delete student."
        );

    } finally {

        setDeleting(false);

    }
};

13. JWT Authorization

Delete operations should be protected with authentication.

Authorization:
Bearer YOUR_JWT_TOKEN

An Axios interceptor can automatically attach the token to the request.

14. PHP Read Student ID

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

if (!$id) {

    http_response_code(400);

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

    exit;
}

15. Check Student Before Delete

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

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

$student = $check->fetch(
    PDO::FETCH_ASSOC
);

if (!$student) {

    http_response_code(404);

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

    exit;
}

Checking first allows the API to return a clear 404 response.

16. PHP DELETE Query

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

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

$deleted = $stmt->rowCount();

The prepared statement safely deletes the selected student.

17. Check Delete Result

if ($deleted === 0) {

    http_response_code(404);

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

    exit;
}

rowCount() can be used to determine whether a row was affected by the DELETE operation.

18. Successful Delete Response

http_response_code(200);

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

The API returns HTTP 200 after a successful deletion.

19. Handle 401 Authentication Error

catch (error) {

    if (
        axios.isAxiosError(error) &&
        error.response?.status === 401
    ) {

        setError(
            "Session expired. Please login again."
        );

    }
}

20. Handle 403 Authorization Error

if (
    axios.isAxiosError(error) &&
    error.response?.status === 403
) {

    setError(
        "You are not allowed to delete this student."
    );
}

Authentication tells us who the user is. Authorization determines whether that user has permission to delete the student.

21. Handle 404 Error

if (
    axios.isAxiosError(error) &&
    error.response?.status === 404
) {

    setError(
        "Student not found."
    );
}

22. Handle General API Errors

catch (error) {

    if (
        axios.isAxiosError(error)
    ) {

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

    } else {

        setError(
            "Network error."
        );
    }
}

23. Remove Student from Local List

When deletion succeeds, the Student List can remove the student from its local state.

setStudents(
    previous =>
        previous.filter(
            student =>
                student.id !== id
        )
);

This avoids making the user wait for another complete list request.

24. Delete from Student List

In many applications, a separate Delete screen is not necessary. The Student List can directly call a confirmation dialog.

const confirmDelete =
    (studentId: number) => {

    Alert.alert(
        "Delete Student",
        "Are you sure?",
        [
            {
                text: "Cancel"
            },
            {
                text: "Delete",
                onPress: () =>
                    deleteStudent(studentId)
            }
        ]
    );
};

25. Loading State During Delete

{deleting && (
    <View>

        <ActivityIndicator
            size="small"
        />

        <Text>
            Deleting student...
        </Text>

    </View>
)}

Showing progress makes it clear that the delete request is being processed.

26. Complete Delete Function

const deleteStudent =
    async (studentId: number) => {

    try {

        setDeleting(true);
        setError("");
        setSuccess("");

        const response =
            await api.delete<DeleteStudentResponse>(
                "/students.php",
                {
                    params: {
                        id: studentId
                    }
                }
            );

        setSuccess(
            response.data.message
        );

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

    } catch (error) {

        if (
            axios.isAxiosError(error)
        ) {

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

        } else {

            setError(
                "Network error."
            );
        }

    } finally {

        setDeleting(false);

    }
};

27. Complete Delete Screen Example

const DeleteStudentScreen =
    ({ route, navigation }: any) => {

    const { id } = route.params;

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

    const [error, setError] =
        useState("");

    const deleteStudent =
        async () => {

        try {

            setDeleting(true);
            setError("");

            await api.delete(
                "/students.php",
                {
                    params: {
                        id
                    }
                }
            );

            Alert.alert(
                "Success",
                "Student deleted successfully."
            );

            navigation.navigate(
                "StudentList"
            );

        } catch (error) {

            if (
                axios.isAxiosError(error)
            ) {

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

            } else {

                setError(
                    "Network error."
                );
            }

        } finally {

            setDeleting(false);

        }
    };

    return (

        <View>

            <Text>
                Delete Student
            </Text>

            <Text>
                Are you sure you want
                to delete this student?
            </Text>

            {error !== "" && (
                <Text>
                    {error}
                </Text>
            )}

            {deleting && (
                <ActivityIndicator />
            )}

            <TouchableOpacity
                onPress={deleteStudent}
            >

                <Text>
                    Delete Student
                </Text>

            </TouchableOpacity>

        </View>
    );
};

28. Important Delete Security Rules

  • Always authenticate the DELETE request.
  • Verify the JWT on the server.
  • Check the user's role and permissions.
  • Validate the student ID.
  • Use prepared statements.
  • Never trust a student ID from the mobile application.
  • Do not allow unauthorized users to delete records.
  • Consider related database records before deletion.
  • Use HTTPS in production.

29. Complete Delete Architecture

Student List
      ↓
Delete Button
      ↓
Confirmation Dialog
      ↓
DELETE /students.php?id=5
      ↓
JWT Verification
      ↓
Authorization Check
      ↓
Validate ID
      ↓
Check Student
      ↓
PDO DELETE
      ↓
HTTP 200
      ↓
Remove from Local State
      ↓
Updated Student List

30. Project Delete Student Summary

The Delete Student functionality completes the CRUD operations for our Student Management application.

  • DELETE is used to remove a student.
  • The student ID identifies the record.
  • Confirmation helps prevent accidental deletion.
  • Axios sends the DELETE request.
  • JWT protects the API.
  • The PHP API validates the ID.
  • The API checks whether the student exists.
  • PDO prepared statements perform the deletion.
  • HTTP 200 indicates successful deletion.
  • HTTP 401 indicates an authentication problem.
  • HTTP 403 indicates insufficient permission.
  • HTTP 404 indicates that the student was not found.
  • The next lesson will add student search functionality.

📌 Key Points

  • Use DELETE to remove an existing student.
  • Ask for confirmation before destructive actions.
  • Pass the student ID to the API.
  • Use Axios for the DELETE request.
  • Protect the API using JWT authentication.
  • Perform authorization checks on the server.
  • Validate the student ID.
  • Use PDO prepared statements.
  • Update the local student list after successful deletion.
  • Handle 401, 403, 404, and network errors.

🧠 Quick Quiz

Question: Which HTTP method is used to delete a student from the REST API?