import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import Navbar from "../Navbar";
import Footer from "../footer";
import './styles.css';
import 'bootstrap/dist/css/bootstrap.min.css';
const AccountCreation = () => {
const [formData, setFormData] = useState({
username: '',
email: '',
password: '',
confirmPassword: '',
dateOfBirth: '',
country: ''
});
const [termsAgreed, setTermsAgreed] = useState(false);
const [countries, setCountries] = useState([]);
const navigate = useNavigate();
// Fetch countries on component mount
useEffect(() => {
const fetchCountries = async () => {
try {
const response = await fetch('https://restcountries.com/v3.1/all');
const data = await response.json();
const countryNames = data.map(country => country.name.common);
setCountries(countryNames.sort()); // Sort the country names alphabetically
} catch (error) {
console.error('Error fetching countries:', error);
}
};
fetchCountries();
}, []);
// Input Handler
const handleInputChange = (e) => {
const { name, value } = e.target;
setFormData((prevData) => ({
...prevData,
[name]: value
}));
};
// Checkbox Handler
const handleCheckboxChange = (e) => {
setTermsAgreed(e.target.checked);
};
// Submit Handler
const handleSubmit = async (e) => {
e.preventDefault();
// Check if passwords match
if (formData.password !== formData.confirmPassword) {
console.log('Passwords do not match!');
alert('Passwords do not match!');
return;
}
const requestData = {
username: formData.username,
email: formData.email,
password: formData.password,
password_repeat: formData.confirmPassword,
dob: formData.dateOfBirth,
country_of_origin: formData.country
};
try {
const response = await fetch('https://jp-backend-kc80.onrender.com/auth/signup', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(requestData),
});
const data = await response.json();
console.error('Server response:', data);
if (response.ok) {
alert('Account created successfully!');
navigate('/login'); // Redirect to login page upon success
} else {
// Error and Detail Alerts
const errorMessage = data.message || 'Unknown error';
let errorDetails = '';
// detail can be both string or array
if (Array.isArray(data.detail)) {
errorDetails = data.detail.map(detail => detail.msg).join(', ');
} else if (typeof data.detail === 'string') {
errorDetails = data.detail;
}
alert(`Error: ${errorMessage}\nDetails: ${errorDetails}`);
}
} catch (error) {
console.error('Error:', error.message || error);
alert('Something went wrong. Please try again later.');
}
};
return (
<>