1 | // CustomerFormContainer.js
|
---|
2 | import React, { useState, useEffect } from 'react';
|
---|
3 | import axios from 'axios';
|
---|
4 | import CustomerForm from './CustomersForm';
|
---|
5 | import MembershipsEnum from "./MembershipsEnum";
|
---|
6 | import {useNavigate, useParams} from "react-router-dom";
|
---|
7 |
|
---|
8 | const CustomerFormContainer = () => {
|
---|
9 | const navigate = useNavigate();
|
---|
10 | const [formData, setFormData] = useState({
|
---|
11 | firstName: '',
|
---|
12 | lastName: '',
|
---|
13 | email: '',
|
---|
14 | password: '',
|
---|
15 | phone: '',
|
---|
16 | address: '',
|
---|
17 | membershipLevel: MembershipsEnum()[0]
|
---|
18 | });
|
---|
19 |
|
---|
20 | const { id } = useParams();
|
---|
21 | const [customer, setCustomer] = useState(null);
|
---|
22 |
|
---|
23 | useEffect(() => {
|
---|
24 | if (id) {
|
---|
25 | // Fetch customer data only if in edit mode
|
---|
26 | const fetchCustomer = async () => {
|
---|
27 | try {
|
---|
28 | const response = await axios.get(`http://localhost:8080/api/customers/${id}`);
|
---|
29 | const customerData = response.data;
|
---|
30 | setFormData({
|
---|
31 | firstName: customerData.firstName || '',
|
---|
32 | lastName: customerData.lastName || '',
|
---|
33 | email: customerData.email || '',
|
---|
34 | password: '', // For security reasons, the password field should not be pre-filled
|
---|
35 | phone: customerData.phone || '',
|
---|
36 | address: customerData.address || '',
|
---|
37 | membershipLevel: customerData.membershipLevel || MembershipsEnum()[0]
|
---|
38 | });
|
---|
39 | } catch (error) {
|
---|
40 | console.error('Error fetching customer:', error);
|
---|
41 | }
|
---|
42 | };
|
---|
43 |
|
---|
44 | fetchCustomer();
|
---|
45 | }
|
---|
46 | }, [id]);
|
---|
47 |
|
---|
48 | const handleChange = (e) => {
|
---|
49 | setFormData({ ...formData, [e.target.name]: e.target.value });
|
---|
50 | };
|
---|
51 |
|
---|
52 | const handleSubmit = async (e) => {
|
---|
53 | e.preventDefault();
|
---|
54 | try {
|
---|
55 | if (customer) {
|
---|
56 | await axios.put(`http://localhost:8080/api/customers/edit/${customer.id}`, formData);
|
---|
57 | } else {
|
---|
58 | await axios.post("http://localhost:8080/api/customers", formData);
|
---|
59 | }
|
---|
60 | navigate("/customers");
|
---|
61 | } catch (error) {
|
---|
62 | navigate("/error");
|
---|
63 | }
|
---|
64 | };
|
---|
65 |
|
---|
66 | return (
|
---|
67 | <CustomerForm
|
---|
68 | formData={formData}
|
---|
69 | handleChange={handleChange}
|
---|
70 | handleSubmit={handleSubmit}
|
---|
71 | membershipOptions={MembershipsEnum()}
|
---|
72 | isEdit={!!customer} // Pass a boolean indicating whether it's an update
|
---|
73 | />
|
---|
74 | );
|
---|
75 | };
|
---|
76 |
|
---|
77 | export default CustomerFormContainer;
|
---|