source: my-react-app/src/components/ReservationEdit.js@ 8ca35dc

main
Last change on this file since 8ca35dc was 8ca35dc, checked in by Aleksandar Panovski <apano77@…>, 4 months ago

Done with stupid timeslots

  • Property mode set to 100644
File size: 6.2 KB
Line 
1import React, { useState, useEffect } from 'react';
2import axios from 'axios';
3import {useNavigate, useParams} from 'react-router-dom';
4import StarRating from "./StarRating";
5import {jwtDecode} from "jwt-decode";
6
7const ReservationEdit = () => {
8 const navigate = useNavigate();
9
10 const [isLoading, setIsLoading] = useState(true);
11 const { reservationId } = useParams(); // Extract reservationId from URL params
12 const [formData, setFormData] = useState({});
13 const [table, setTable] = useState({});
14 const [restaurant, setRestaurant] = useState({});
15 const [timeSlots, setTimeSlots] = useState([]);
16 const [filteredTimeSlots, setFilteredTimeSlots] = useState([]);
17 const [checkInTime, setCheckInTime] = useState([]);
18
19 useEffect(() => {
20 const fetchReservation = async () => {
21 try {
22 setIsLoading(true);
23 const response = await axios.get(`http://localhost:8081/api/reservations/${reservationId}`);
24 setCheckInTime(response.data.checkInTime)
25 setFormData(response.data);
26 setTable(response.data.table);
27 setRestaurant(response.data.restaurant);
28 setTimeSlots(response.data.table.timeSlots);
29 setIsLoading(false);
30 } catch (error) {
31 console.error('Error fetching reservation:', error);
32 }
33 };
34 fetchReservation();
35 }, [reservationId]);
36
37 useEffect(() => {
38 if (!table || !restaurant) return; // If table or restaurant is not loaded, return early
39
40 const currentTime = new Date();
41
42 const filteredSlots = timeSlots.filter(timeSlot => new Date(timeSlot) >= currentTime);
43 setFilteredTimeSlots(filteredSlots);
44 }, [table, restaurant]);
45
46 const handleInputChange = (e) => {
47 const { name, value } = e.target;
48
49 // Check if the changed input is the time slot select element
50 if (name === 'selectedTimeSlot') {
51 // Update the formData with the selected time slot value
52 setFormData({ ...formData, checkInTime: value });
53 } else {
54 // For other input fields, update formData as usual
55 setFormData({ ...formData, [name]: value });
56 }
57 };
58
59 const handleSubmit = async (e) => {
60 e.preventDefault();
61
62 try {
63 const token = localStorage.getItem("token");
64 if (!token) {
65 console.error("No token found");
66 return;
67 }
68
69 const decodedToken = jwtDecode(token);
70 console.log(decodedToken)
71 const userId = decodedToken.iss;
72
73 await axios.post(`http://localhost:8081/api/reservations/${reservationId}/${userId}`, formData);
74
75 navigate(`/reservations`)
76 } catch (error) {
77 console.error('Error updating reservation:', error);
78 }
79 };
80
81 const formatTimeSlot = (timeSlot) => {
82 const date = new Date(timeSlot);
83 const formattedDate = date.toLocaleDateString();
84 const formattedTime = date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
85 return `${formattedDate} - ${formattedTime}`;
86 };
87
88 const formatCurrentTimeSlot = (timeSlot) => {
89 const date = new Date(timeSlot);
90 const formattedDate = date.toLocaleDateString('en-GB'); // Format date as YYYY-MM-DD
91 const formattedTime = date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); // Format time as HH:MM
92 return `${formattedDate} ${formattedTime}`;
93 };
94
95 return (
96 <div className="container">
97 {isLoading ? ( // Conditional rendering based on loading state
98 <p>Loading...</p>
99 ) : (
100 <>
101 <h1>Edit Reservation</h1>
102 <div className="card-body">
103 <h2>
104 {restaurant.name} <StarRating key={restaurant.id} rating={restaurant.rating}/>
105 </h2>
106 <p className="card-text">{restaurant.cuisineType}</p>
107 <p className="card-text">{restaurant.operatingHours}</p>
108 <p className="card-text">Ul. {restaurant.address}</p>
109 <br/>
110 </div>
111 <form onSubmit={handleSubmit}>
112 <div className="mb-3">
113 <label htmlFor="checkInTime" className="form-label">Check-in Time</label>
114 <select className="form-select mt-2" aria-label="Select Time Slot"
115 name="selectedTimeSlot" // Add name attribute
116 onChange={handleInputChange}>
117 <option value="">Select Time Slot</option>
118 {filteredTimeSlots.map((timeSlot, index) => (
119 <option key={index} value={timeSlot}>{formatTimeSlot(timeSlot)}</option>
120 ))}
121 </select>
122 <label className=".text-danger">Current check in time: {formatTimeSlot(checkInTime)}</label>
123 </div>
124 <div className="mb-3">
125 <label htmlFor="partySize" className="form-label">Party Size</label>
126 <input type="number" className="form-control" id="partySize" name="partySize"
127 max={table.capacity}
128 value={formData.partySize || ''} onChange={handleInputChange}/>
129 </div>
130 <div className="mb-3">
131 <label htmlFor="specialRequests" className="form-label">Special Requests</label>
132 <input type="text" className="form-control" id="specialRequests" name="specialRequests"
133 value={formData.specialRequests || ''} onChange={handleInputChange}/>
134 </div>
135 <button type="submit" className="btn btn-primary">Submit</button>
136 </form>
137 </>
138 )}
139 </div>
140 );
141
142};
143
144export default ReservationEdit;
Note: See TracBrowser for help on using the repository browser.