1. Home
  2. Docs
  3. Django Rest Framework
  4. Frontent

Frontent

StudentAdd Component

This component is for adding new students.

import React, { useState } from 'react';
import axios from 'axios';

const StudentAdd = () => {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [picture, setPicture] = useState(null);

  const handleSubmit = async (e) => {
    e.preventDefault();
    const formData = new FormData();
    formData.append('name', name);
    formData.append('email', email);
    if (picture) formData.append('picture', picture);

    try {
      await axios.post(process.env.REACT_APP_API_URL, formData, {
        headers: { 'Content-Type': 'multipart/form-data' },
      });
      // Reset form or give feedback
      setName('');
      setEmail('');
      setPicture(null);
      alert('Student added successfully!');
    } catch (error) {
      console.error('Error adding student:', error);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <input type="text" placeholder="Name" value={name} onChange={e => setName(e.target.value)} />
      <input type="email" placeholder="Email" value={email} onChange={e => setEmail(e.target.value)} />
      <input type="file" onChange={e => setPicture(e.target.files[0])} />
      <button type="submit">Add Student</button>
    </form>
  );
};

export default StudentAdd;
JavaScript

StudentList

import React, { useEffect, useState } from 'react';
import axios from 'axios';

const StudentList = () => {
  const [students, setStudents] = useState([]);

  useEffect(() => {
    const fetchStudents = async () => {
      try {
        const { data } = await axios.get(process.env.REACT_APP_API_URL);
        setStudents(data);
      } catch (error) {
        console.error('Failed to fetch students:', error);
      }
    };

    fetchStudents();
  }, []);

  const handleDelete = async (studentId) => {
    try {
      await axios.delete(`${process.env.REACT_APP_API_URL}${studentId}/`);
      // Refresh the list by filtering out the deleted student
      setStudents(students.filter(student => student.id !== studentId));
    } catch (error) {
      console.error('Failed to delete the student:', error);
    }
  };

  return (
    <div>
      <h2>Student List</h2>
      {students.map((student) => (
        <div key={student.id}>
          <p>{student.name} - {student.email}</p>
          {student.picture && <img src={student.picture} alt="Student" style={{ width: "100px", height: "auto" }} />}
          <button onClick={() => alert(`Edit student with ID ${student.id} here.`)}>Edit</button>
          <button onClick={() => handleDelete(student.id)}>Delete</button>
        </div>
      ))}
    </div>
  );
};

export default StudentList;
JavaScript

StudentEdit

import React, { useState, useEffect } from 'react';
import axios from 'axios';

const StudentEdit = ({ studentId }) => {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [picture, setPicture] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const { data } = await axios.get(`${process.env.REACT_APP_API_URL}${studentId}/`);
        setName(data.name);
        setEmail(data.email);
        // The picture is not directly fetched; this is just to update text fields
      } catch (error) {
        console.error("Failed to fetch student's data:", error);
      }
    };

    if (studentId) {
      fetchData();
    }
  }, [studentId]);

  const handleSubmit = async (e) => {
    e.preventDefault();
    const formData = new FormData();
    formData.append('name', name);
    formData.append('email', email);
    if (picture) {
      formData.append('picture', picture);
    }

    try {
      await axios.put(`${process.env.REACT_APP_API_URL}${studentId}/`, formData, {
        headers: { 'Content-Type': 'multipart/form-data' },
      });
      alert('Student updated successfully!');
      // Optionally, clear form or navigate away
    } catch (error) {
      console.error("Failed to update the student's data:", error);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <label>Name:</label>
        <input type="text" value={name} onChange={(e) => setName(e.target.value)} />
      </div>
      <div>
        <label>Email:</label>
        <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
      </div>
      <div>
        <label>Picture:</label>
        <input type="file" onChange={(e) => setPicture(e.target.files[0])} />
      </div>
      <button type="submit">Update Student</button>
    </form>
  );
};

export default StudentEdit;
JavaScript

How can we help?