OneCompiler

ReactJs

119

// src/services/api.js
import axios from 'axios';

const API_URL = 'http://localhost:8081/api';

// Create axios instance with default config
const axiosInstance = axios.create({
baseURL: API_URL,
headers: {
'Content-Type': 'application/json',
},
});

// Add request interceptor
axiosInstance.interceptors.request.use(
(config) => {
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = Bearer ${token};
}
return config;
},
(error) => {
return Promise.reject(error);
}
);

// Add response interceptor
axiosInstance.interceptors.response.use(
(response) => response.data,
(error) => {
if (error.response) {
// Handle specific error cases
switch (error.response.status) {
case 401:
// Handle unauthorized
localStorage.removeItem('token');
localStorage.removeItem('user');
window.location.href = '/login';
break;
case 403:
// Handle forbidden
break;
default:
break;
}
return Promise.reject(error.response.data);
}
return Promise.reject(error);
}
);

export const api = {
login: async (credentials) => {
try {
const response = await axiosInstance.post('/users/login', credentials);
localStorage.setItem('token', response.token);
return response;
} catch (error) {
throw new Error(error.message || 'Login failed');
}
},

getCourses: async () => {
try {
return await axiosInstance.get('/courses/published');
} catch (error) {
throw new Error(error.message || 'Failed to fetch courses');
}
},

getCourseById: async (id) => {
try {
return await axiosInstance.get(/courses/${id});
} catch (error) {
throw new Error(error.message || 'Failed to fetch course');
}
},

enrollInCourse: async (studentId, courseId) => {
try {
return await axiosInstance.post('/enrollments', { studentId, courseId });
} catch (error) {
throw new Error(error.message || 'Enrollment failed');
}
},

getEnrollments: async (studentId) => {
try {
return await axiosInstance.get(/enrollments/student/${studentId});
} catch (error) {
throw new Error(error.message || 'Failed to fetch enrollments');
}
},

updateProgress: async (enrollmentId, progress) => {
try {
return await axiosInstance.put(/enrollments/${enrollmentId}/progress, { progress });
} catch (error) {
throw new Error(error.message || 'Failed to update progress');
}
}
};

// src/components/Login.js
import React, { useState } from 'react';
import { useAuth } from '../context/AuthContext';
import { api } from '../services/api';
import { useNavigate } from 'react-router-dom';

export const Login = () => {
const [credentials, setCredentials] = useState({ email: '', password: '' });
const [error, setError] = useState('');
const [loading, setLoading] = useState(false);
const { login } = useAuth();
const navigate = useNavigate();

const handleSubmit = async (e) => {
e.preventDefault();
setLoading(true);
setError('');

try {
  const response = await api.login(credentials);
  login(response.user);
  navigate('/dashboard');
} catch (err) {
  setError(err.message || 'Invalid credentials');
} finally {
  setLoading(false);
}

};

return (
<div className="min-h-screen flex items-center justify-center bg-gray-50">
<div className="max-w-md w-full p-6 bg-white rounded-lg shadow-lg">
<h2 className="text-2xl font-bold mb-6 text-center">Login</h2>
{error && (
<div className="bg-red-100 text-red-700 p-3 rounded mb-4">{error}</div>
)}
<form onSubmit={handleSubmit}>
<div className="mb-4">
<label className="block text-gray-700 mb-2">Email</label>
<input
type="email"
className="w-full p-2 border rounded"
value={credentials.email}
onChange={(e) => setCredentials({...credentials, email: e.target.value})}
required
/>
</div>
<div className="mb-6">
<label className="block text-gray-700 mb-2">Password</label>
<input
type="password"
className="w-full p-2 border rounded"
value={credentials.password}
onChange={(e) => setCredentials({...credentials, password: e.target.value})}
required
/>
</div>
<button type="submit" className="w-full bg-blue-500 text-white p-2 rounded hover:bg-blue-600" disabled={loading} >
{loading ? 'Logging in...' : 'Login'}
</button>
</form>
</div>
</div>
);
};

// src/components/CourseList.js
import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { api } from '../services/api';

export const CourseList = () => {
const [courses, setCourses] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');

useEffect(() => {
loadCourses();
}, []);

const loadCourses = async () => {
try {
const data = await api.getCourses();
setCourses(data);
} catch (err) {
setError(err.message || 'Failed to load courses');
} finally {
setLoading(false);
}
};

if (loading) return <div className="text-center p-6">Loading courses...</div>;
if (error) return <div className="text-red-600 text-center p-6">{error}</div>;

return (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 p-6">
{courses.map((course) => (
<div key={course.id} className="border rounded-lg p-4 shadow-sm">
<h3 className="text-xl font-semibold mb-2">{course.title}</h3>
<p className="text-gray-600 mb-4">{course.description}</p>
<div className="flex justify-between items-center">
<span className="text-lg font-bold">{course.price}</span> <Link to={`/courses/{course.id}`}
className="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600"
>
View Details
</Link>
</div>
</div>
))}
</div>
);
};

// src/components/CourseDetail.js
import React, { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';
import { api } from '../services/api';
import { useAuth } from '../context/AuthContext';

export const CourseDetail = () => {
const [course, setCourse] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
const [enrolling, setEnrolling] = useState(false);
const { id } = useParams();
const { user } = useAuth();

useEffect(() => {
loadCourse();
}, [id]);

const loadCourse = async () => {
try {
const data = await api.getCourseById(id);
setCourse(data);
} catch (err) {
setError(err.message || 'Failed to load course');
} finally {
setLoading(false);
}
};

const handleEnroll = async () => {
setEnrolling(true);
try {
await api.enrollInCourse(user.id, id);
// Handle successful enrollment
} catch (err) {
setError(err.message || 'Failed to enroll');
} finally {
setEnrolling(false);
}
};

if (loading) return <div className="text-center p-6">Loading...</div>;
if (error) return <div className="text-red-600 text-center p-6">{error}</div>;
if (!course) return <div className="text-center p-6">Course not found</div>;

return (
<div className="max-w-4xl mx-auto p-6">
<h2 className="text-3xl font-bold mb-4">{course.title}</h2>
<div className="bg-white rounded-lg shadow-lg p-6">
<p className="text-gray-600 mb-4">{course.description}</p>
<div className="mb-4">
<h3 className="text-xl font-semibold mb-2">Instructor</h3>
<p>{course.instructor.fullName}</p>
</div>
<div className="mb-6">
<h3 className="text-xl font-semibold mb-2">Price</h3>
<p className="text-2xl font-bold">${course.price}</p>
</div>
{user && user.role === 'STUDENT' && (
<button onClick={handleEnroll} className="bg-blue-500 text-white px-6 py-2 rounded hover:bg-blue-600 disabled:bg-blue-300" disabled={enrolling} >
{enrolling ? 'Enrolling...' : 'Enroll Now'}
</button>
)}
</div>
</div>
);
};

// src/components/Dashboard.js
import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import { api } from '../services/api';
import { useAuth } from '../context/AuthContext';

export const Dashboard = () => {
const [enrollments, setEnrollments] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
const { user } = useAuth();

useEffect(() => {
loadEnrollments();
}, []);

const loadEnrollments = async () => {
try {
const data = await api.getEnrollments(user.id);
setEnrollments(data);
} catch (err) {
setError(err.message || 'Failed to load enrollments');
} finally {
setLoading(false);
}
};

const handleUpdateProgress = async (enrollmentId, progress) => {
try {
await api.updateProgress(enrollmentId, progress);
loadEnrollments(); // Reload enrollments to get updated data
} catch (err) {
setError(err.message || 'Failed to update progress');
}
};

if (loading) return <div className="text-center p-6">Loading...</div>;
if (error) return <div className="text-red-600 text-center p-6">{error}</div>;

return (
<div className="max-w-4xl mx-auto p-6">
<h2 className="text-2xl font-bold mb-6">My Courses</h2>
<div className="grid gap-6">
{enrollments.map((enrollment) => (
<div key={enrollment.id} className="border rounded-lg p-4 shadow-sm">
<h3 className="text-xl font-semibold mb-2">
{enrollment.course.title}
</h3>
<div className="flex flex-col md:flex-row justify-between items-center gap-4">
<div className="w-full md:w-2/3">
<div className="bg-gray-200 rounded-full h-2.5">
<div
className="bg-blue-600 h-2.5 rounded-full"
style={{ width: ${enrollment.progress}% }}
></div>
</div>
<span className="text-sm text-gray-600">
Progress: {enrollment.progress}%
</span>
</div>
<Link
to={/courses/${enrollment.course.id}}
className="text-blue-500 hover:text-blue-600"
>
Continue Learning
</Link>
</div>
</div>
))}
</div>
</div>
);
};