source: my-react-app/src/components/CustomerFormContainer.js@ 65b6638

main
Last change on this file since 65b6638 was d24f17c, checked in by Aleksandar Panovski <apano77@…>, 15 months ago

Initial commit

  • Property mode set to 100644
File size: 2.6 KB
Line 
1// CustomerFormContainer.js
2import React, { useState, useEffect } from 'react';
3import axios from 'axios';
4import CustomerForm from './CustomersForm';
5import MembershipsEnum from "./MembershipsEnum";
6import {useNavigate, useParams} from "react-router-dom";
7
8const 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
77export default CustomerFormContainer;
Note: See TracBrowser for help on using the repository browser.