DEV Community

mesCode
mesCode

Posted on

How to setup React fetching and Context API with Axios mesCode

In this guide, we are configuring the basic React flow.

  1. You need Node.js installed on your system. node -v (Check if you have it by running) If it is not installed, download it from the Official Node.js

2.Run the initialization command to create
*npm create vite@latest my-react-app -- --template react
*
(Replace my-react-app with your preferred project name)

3.Move into your new project directory and install the required packages
cd my-react-app
npm install

  1. Launch your local live-reload development server npm run dev
  2. place and see this example `import { useState, useEffect } from 'react'; import './App.css';

const API_BASE_URL = "https://localhost:7278/api/Student";

function App() {
const [students, setStudents] = useState([]);
const [courses, setCourses] = useState([]);

const [studentID, setStudentID] = useState(0);
const [studentName, setStudentName] = useState("");
const [email, setEmail] = useState("");
const [phone, setPhone] = useState("");
const [gender, setGender] = useState("Male");
const [address, setAddress] = useState("");
const [rank, setRank] = useState(0);
const [dob, setDob] = useState("");
const [courseID, setCourseID] = useState("");

const [isEditing, setIsEditing] = useState(false);

useEffect(() => {
fetchStudents();
fetchCourses();
}, []);

async function fetchStudents() {
try {
const response = await fetch(${API_BASE_URL}/student);
if (response.ok) {
const data = await response.json();
setStudents(data);
}
} catch (error) {
console.error("Error fetching students:", error);
}
}

async function fetchCourses() {
try {
const response = await fetch(${API_BASE_URL}/course);
if (response.ok) {
const data = await response.json();
setCourses(data);
if (data.length > 0 && !courseID) {
setCourseID(data[0].courseID);
}
}
} catch (error) {
console.error("Error fetching courses:", error);
}
}

async function handleSubmit(e) {
debugger;
e.preventDefault();

if (!studentName || !email || !courseID) {
  alert("Please Fill the Requred Fields (Name, Email, Course)!!");
  return;
}

const studentPayload = {
  studentID: isEditing ? studentID : 0,
  studentName: studentName,
  email: email,
  phone: phone,
  gender: gender,
  address: address,
  rank: parseFloat(rank),
  dob: dob ? new Date(dob).toISOString() : new Date().toISOString(),
  courseID: parseInt(courseID)
};

try {
  let response;
  if (isEditing) {
    response = await fetch(`${API_BASE_URL}/${studentID}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(studentPayload)
    });
  } else {
    response = await fetch(API_BASE_URL, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(studentPayload)
    });
  }

  if (response.ok) {
    fetchStudents(); 
    clearForm();
  } else {
    const errMsg = await response.text();
    alert("Error: " + errMsg);
  }
} catch (error) {
  console.error("Submit error:", error);
}
Enter fullscreen mode Exit fullscreen mode

}

function handleEdit(student) {
setIsEditing(true);
setStudentID(student.studentID);
setStudentName(student.studentName);
setEmail(student.email);
setPhone(student.phone);
setGender(student.gender);
setAddress(student.address);
setRank(student.rank);
setDob(student.dob ? student.dob.split('T')[0] : "");
setCourseID(student.courseID);
}

async function handleDelete(id) {
if (window.confirm("Are You Sure??")) {
try {
const response = await fetch(${API_BASE_URL}/${id}, {
method: 'DELETE'
});
if (response.ok) {
fetchStudents();
}
} catch (error) {
console.error("Delete error:", error);
}
}
}

function clearForm() {
setIsEditing(false);
setStudentID(0);
setStudentName("");
setEmail("");
setPhone("");
setGender("Male");
setAddress("");
setRank(0);
setDob("");
if (courses.length > 0) setCourseID(courses[0].courseID);
}

return (


Student Management System (CRUD)

  {/* --- FORM SECTION --- */}
  <form onSubmit={handleSubmit} style={{ border: '1px solid #ccc', padding: '20px', borderRadius: '8px', marginBottom: '30px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '15px' }}>
    <h3 style={{ gridColumn: 'span 2', margin: '0 0 10px 0' }}>{isEditing ? "✏️ Edit Student Details" : "➕ Register New Student"}</h3>

    <div>
      <label>Student Name *</label>
      <input type="text" value={studentName} onChange={(e) => setStudentName(e.target.value)} style={{ width: '100%', padding: '8px', marginTop: '5px' }} />
    </div>

    <div>
      <label>Email Address *</label>
      <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} style={{ width: '100%', padding: '8px', marginTop: '5px' }} />
    </div>

    <div>
      <label>Phone Number</label>
      <input type="text" value={phone} onChange={(e) => setPhone(e.target.value)} style={{ width: '100%', padding: '8px', marginTop: '5px' }} />
    </div>

    <div>
      <label>Gender</label>
      <select value={gender} onChange={(e) => setGender(e.target.value)} style={{ width: '100%', padding: '8px', marginTop: '5px' }}>
        <option value="Male">Male</option>
        <option value="Female">Female</option>
      </select>
    </div>

    <div>
      <label>Date of Birth</label>
      <input type="date" value={dob} onChange={(e) => setDob(e.target.value)} style={{ width: '100%', padding: '8px', marginTop: '5px' }} />
    </div>

    <div>
      <label>Rank / Marks</label>
      <input type="number" step="0.01" value={rank} onChange={(e) => setRank(e.target.value)} style={{ width: '100%', padding: '8px', marginTop: '5px' }} />
    </div>

    <div>
      <label>Select Course *</label>
      <select 
        value={courseID} 
        onChange={(e) => setCourseID(e.target.value)} 
        style={{ width: '100%', padding: '8px', marginTop: '5px', backgroundColor: '#968206', border: '1px solid rgb(19, 19, 15)' }}
      >
        <option value="">-- Choose Course --</option>
        {courses.map((course) => (
          <option key={course.courseID} value={course.courseID}>
            {course.courseName}
          </option>
        ))}
      </select>
    </div>

    <div style={{ gridColumn: 'span 2' }}>
      <label>Address</label>
      <textarea value={address} onChange={(e) => setAddress(e.target.value)} style={{ width: '100%', padding: '8px', marginTop: '5px', height: '60px' }}></textarea>
    </div>

    <div style={{ gridColumn: 'span 2', marginTop: '10px' }}>
      <button type="submit" style={{ padding: '10px 20px', backgroundColor: '#28a745', color: '#fff', border: 'none', cursor: 'pointer', borderRadius: '4px' }}>
        {isEditing ? "Update Student" : "Register Student"}
      </button>
      {isEditing && (
        <button type="button" onClick={clearForm} style={{ marginLeft: '10px', padding: '10px 20px', backgroundColor: '#6c757d', color: '#fff', border: 'none', cursor: 'pointer', borderRadius: '4px' }}>
          Cancel
        </button>
      )}
    </div>
  </form>

  {/* --- TABLE SECTION --- */}
  <h3>Registered Students</h3>
  <table border="1" cellPadding="10" style={{ width: '100%', borderCollapse: 'collapse', textAlign: 'left' }}>
    <thead>
      <tr style={{ backgroundColor: '#f8f9fa' }}>
        <th>ID</th>
        <th>Name</th>
        <th>Email</th>
        <th>Phone</th>
        <th>Address</th>
        <th>Gender</th>
        <th>Course</th>
        <th>Rank</th>
        <th>Actions</th>
      </tr>
    </thead>
    <tbody>
      {students.length > 0 ? (
        students.map((student) => (
          <tr key={student.studentID}>
            <td>{student.studentID}</td>
            <td>{student.studentName}</td>
            <td>{student.email}</td>
            <td>{student.phone}</td>
            <td>{student.address}</td>
            <td>{student.gender}</td>
            <td style={{ fontWeight: 'bold', color: '#0056b3' }}>{student.courseName}</td>
            <td>{student.rank}</td>
            <td>
              <button onClick={() => handleEdit(student)} style={{ marginRight: '5px', backgroundColor: '#ffc107', border: 'none', padding: '5px 10px', cursor: 'pointer' }}>Edit</button>
              <button onClick={() => handleDelete(student.studentID)} style={{ backgroundColor: '#dc3545', color: '#fff', border: 'none', padding: '5px 10px', cursor: 'pointer' }}>Delete</button>
            </td>
          </tr>
        ))
      ) : (
        <tr>
          <td colSpan="7" style={{ textAlign: 'center' }}>No students registered yet.</td>
        </tr>
      )}
    </tbody>
  </table>
</div>

);
}

export default App;`

Top comments (0)