JourneyPoint / journeypoint / frontend / src / Components / signup / AccountCreation.js
AccountCreation.js
Raw
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 (
    <>
      <Navbar />
      <div className="mask">
        <div className="container mt-5">
          <div className="row d-flex justify-content-center align-items-center">
            <div className="col-12 col-md-9 col-lg-7 col-xl-6">
              <div className="card">
                <div className="card-body">
                  <h2 className="text-uppercase text-center mb-5">Create an account</h2>
                  <form onSubmit={handleSubmit}>
                    <div className="form-outline mb-4">
                      <input
                        type="text"
                        id="form3Example1cg"
                        name="username"
                        value={formData.username}
                        onChange={handleInputChange}
                        className="form-control form-control-lg"
                        required
                      />
                      <label className="form-label" htmlFor="form3Example1cg">
                        Username
                      </label>
                    </div>

                    <div className="form-outline mb-4">
                      <input
                        type="email"
                        id="form3Example3cg"
                        name="email"
                        value={formData.email}
                        onChange={handleInputChange}
                        className="form-control form-control-lg"
                        required
                      />
                      <label className="form-label" htmlFor="form3Example3cg">
                        Your Email
                      </label>
                    </div>

                    <div className="form-outline mb-4">
                      <input
                        type="password"
                        id="form3Example4cg"
                        name="password"
                        value={formData.password}
                        onChange={handleInputChange}
                        className="form-control form-control-lg"
                        required
                      />
                      <label className="form-label" htmlFor="form3Example4cg">
                        Password
                      </label>
                    </div>

                    <div className="form-outline mb-4">
                      <input
                        type="password"
                        id="form3Example4cdg"
                        name="confirmPassword"
                        value={formData.confirmPassword}
                        onChange={handleInputChange}
                        className="form-control form-control-lg"
                        required
                      />
                      <label className="form-label" htmlFor="form3Example4cdg">
                        Repeat your password
                      </label>
                    </div>

                    <div className="form-outline mb-4">
                      <input
                        type="date"
                        id="form3Example5cg"
                        name="dateOfBirth"
                        value={formData.dateOfBirth}
                        onChange={handleInputChange}
                        className="form-control form-control-lg"
                        required
                      />
                      <label className="form-label" htmlFor="form3Example5cg">
                        Date of Birth
                      </label>
                    </div>

                    {/* Country Dropdown */}
                    <div className="form-outline mb-4">
                      <select
                        id="form3Example6cg"
                        name="country"
                        value={formData.country}
                        onChange={handleInputChange}
                        className="form-control form-control-lg"
                        required
                      >
                        <option value="">Select a Country</option>
                        {countries.map((country, index) => (
                          <option key={index} value={country}>
                            {country}
                          </option>
                        ))}
                      </select>
                      <label className="form-label" htmlFor="form3Example6cg">
                        Country of Origin
                      </label>
                    </div>

                    <div className="d-flex justify-content-center">
                      <button
                        type="submit"
                        data-mdb-button-init
                        data-mdb-ripple-init
                        className="btn btn-success btn-block btn-lg gradient-custom-4 text-body"
                      >
                        Register
                      </button>
                    </div>

                    <p className="text-center text-muted mt-5 mb-0">
                      Have an account already?{' '}
                      <a href="http://www.journeypoint.ddnsfree.com/login" className="fw-bold text-body">
                        <u>Login here</u>
                      </a>
                    </p>
                  </form>
                </div>
              </div>
            </div>
          </div>
        </div>
        <Footer />
      </div>
    </>
  );
};

export default AccountCreation;