Changeset 8ca35dc for my-react-app/src/components
- Timestamp:
- 01/19/25 23:18:37 (4 months ago)
- Branches:
- main
- Children:
- f5b256e
- Parents:
- db39d9e
- Location:
- my-react-app/src/components
- Files:
-
- 2 added
- 16 edited
Legend:
- Unmodified
- Added
- Removed
-
my-react-app/src/components/AppContent.js
rdb39d9e r8ca35dc 1 import * as React from "react"; 1 import React from "react"; 2 import axios from "axios"; 2 3 import WelcomeContent from "./WelcomeContent"; 3 4 import AuthContent from "./AuthContent"; 4 5 import LoginForm from "./LoginForm"; 5 import { request, setAuthToken } from "../axios_helper"; 6 import Buttons from './Buttons' 6 import AuthForm from "./AuthForm"; 7 import Buttons from './Buttons'; 8 import restaurants from "./Restaurants"; 7 9 8 export defaultclass AppContent extends React.Component {10 class AppContent extends React.Component { 9 11 constructor(props) { 10 12 super(props); 11 13 this.state = { 12 componentToShow: "welcome" 14 componentToShow: "welcome", 15 isAuthenticated: false, 16 user: null, 17 loading: false // Add loading state 13 18 }; 19 } 20 21 componentDidMount() { 22 const token = localStorage.getItem('token'); 23 console.log(token); 24 if (token) { 25 this.setAuthToken(token); 26 this.setState({ componentToShow: "restaurants", isAuthenticated: true }); 27 } 28 } 29 30 fetchUserDetails = (token) => { 31 console.log("Fetch"); 32 axios.get("/api/user") 33 .then((response) => { 34 this.setState({ user: response.data, componentToShow: "restaurants", isAuthenticated: true }); 35 }) 36 .catch((error) => { 37 console.error("Failed to fetch user details:", error); 38 this.logout(); 39 }); 14 40 }; 15 41 16 42 login = () => { 17 this.setState({ componentToShow: "login"})43 this.setState({ componentToShow: "login" }); 18 44 } 19 45 20 46 logout = () => { 21 this.setState({componentToShow: "welcome"}) 47 localStorage.removeItem('token'); 48 this.setAuthToken(null); 49 this.setState({ componentToShow: "welcome", isAuthenticated: false }); 22 50 } 23 51 24 52 onLogin = (e, email, password) => { 25 53 e.preventDefault(); 26 request( 27 "POST", 28 "/api/login", 29 {email: email, password: password} 30 ).then((response) => { 31 this.setState({componentToShow: "restaurants"}) 32 setAuthToken(response.data.token); 33 }).catch((error) => { 34 this.setState({componentToShow: "welcome"}) 35 }); 54 // After successful login, save the token 55 axios.post("/api/login", { email, password }) 56 .then((response) => { 57 const token = response.data.token; 58 localStorage.setItem('token', token); // Save the token 59 console.log(token); 60 this.setAuthToken(token); // Set the token for future requests 61 this.setState({ componentToShow: "restaurants", isAuthenticated: true }); 62 }) 63 .catch((error) => { 64 console.error("Login failed:", error); 65 this.setState({ componentToShow: "welcome" }); 66 }); 67 36 68 }; 37 69 38 70 onRegister = (e, firstName, lastName, email, password) => { 39 71 e.preventDefault(); 40 request( 41 "POST", 42 "/api/register", 43 { 44 firstName: firstName, 45 lastName: lastName, 46 email: email, 47 password: password 48 } 49 ).then((response) => { 50 this.setState({componentToShow: "restaurants"}) 51 setAuthToken(response.data.token); 52 }).catch((error) => { 53 this.setState({componentToShow: "welcome"}) 54 }); 72 axios.post("/api/register", { firstName, lastName, email, password }) 73 .then((response) => { 74 const token = response.data.token; 75 localStorage.setItem('token', token); 76 console.log(token); 77 this.setAuthToken(token); 78 this.fetchUserDetails(token); 79 }) 80 .catch((error) => { 81 this.setState({ componentToShow: "welcome" }); 82 console.error(error); 83 }); 84 }; 85 86 setAuthToken = (token) => { 87 if (token) { 88 axios.defaults.headers.common["Authorization"] = `Bearer ${token}`; 89 } else { 90 delete axios.defaults.headers.common["Authorization"]; 91 } 55 92 }; 56 93 … … 58 95 return ( 59 96 <div> 60 <Buttons login={this.login} logout={this.logout}></Buttons> 61 {this.state.componentToShow === "welcome" && <WelcomeContent/>} 62 {this.state.componentToShow === "restaurants" && <AuthContent/>} 63 {this.state.componentToShow === "login" && <LoginForm onLogin={this.onLogin} onRegister={this.onRegister}/>} 97 <Buttons login={this.login} logout={this.logout} /> 98 {this.state.componentToShow === "welcome" && <WelcomeContent />} 99 {this.state.componentToShow === "restaurants" && <AuthContent />} 100 {this.state.componentToShow === "login" && <LoginForm onLogin={this.onLogin} onRegister={this.onRegister} />} 101 {this.state.loading && <div>Loading...</div>} {/* Show loading state */} 64 102 </div> 65 ) 103 ); 66 104 } 67 105 } 106 107 108 export default AppContent; -
my-react-app/src/components/AuthContent.js
rdb39d9e r8ca35dc 28 28 <p>Cuisine Type: {restaurant.cuisineType}</p> 29 29 <p>Address: {restaurant.address}</p> 30 30 <p>User: {}</p> 31 31 </div> 32 32 ))} -
my-react-app/src/components/CuisineContext.js
rdb39d9e r8ca35dc 10 10 const fetchCuisineTypes = async () => { 11 11 try { 12 const response = await axios.get('http://localhost:808 0/api/cuisineTypes');12 const response = await axios.get('http://localhost:8081/api/cuisineTypes'); 13 13 setCuisineTypes(response.data); 14 14 } catch (error) { -
my-react-app/src/components/CustomerContext.js
rdb39d9e r8ca35dc 10 10 const fetchCustomers = async () => { 11 11 try { 12 const response = await axios.get("http://localhost:808 0/api/customers");12 const response = await axios.get("http://localhost:8081/api/customers"); 13 13 setCustomers(response.data) 14 14 } catch (error) { -
my-react-app/src/components/CustomerDetails.js
rdb39d9e r8ca35dc 10 10 const fetchCustomer = async () => { 11 11 try { 12 const response = await axios.get(`http://localhost:808 0/api/customers/${id}`);12 const response = await axios.get(`http://localhost:8081/api/customers/${id}`); 13 13 setCustomer(response.data); 14 14 } catch (error) { -
my-react-app/src/components/CustomerFormContainer.js
rdb39d9e r8ca35dc 26 26 const fetchCustomer = async () => { 27 27 try { 28 const response = await axios.get(`http://localhost:808 0/api/customers/${id}`);28 const response = await axios.get(`http://localhost:8081/api/customers/${id}`); 29 29 const customerData = response.data; 30 30 setFormData({ … … 54 54 try { 55 55 if (customer) { 56 await axios.put(`http://localhost:808 0/api/customers/edit/${customer.id}`, formData);56 await axios.put(`http://localhost:8081/api/customers/edit/${customer.id}`, formData); 57 57 } else { 58 await axios.post("http://localhost:808 0/api/customers", formData);58 await axios.post("http://localhost:8081/api/customers", formData); 59 59 } 60 60 navigate("/customers"); -
my-react-app/src/components/Customers.js
rdb39d9e r8ca35dc 26 26 const handleDeleteClick = async (customerId) => { 27 27 try { 28 await axios.delete(`http://localhost:808 0/api/customers/delete/${customerId}`);28 await axios.delete(`http://localhost:8081/api/customers/delete/${customerId}`); 29 29 setCustomers(customers.filter(customer => customer.customerID !== customerId)); 30 30 window.location.reload(); … … 48 48 <p className="card-text"><strong>Phone:</strong> {customer.phone}</p> 49 49 <p className="card-text"><strong>Address:</strong> {customer.address}</p> 50 <p className="card-text"><strong>Membership 51 Level:</strong> {customer.membershipLevel}</p> 50 <p className="card-text"><strong>Membership Level:</strong> {customer.membershipLevel}</p> 52 51 {/*<p className="card-text"><strong>Registration*/} 53 52 {/* Date:</strong> {new Date(customer.registrationDate).toLocaleString()}</p>*/} -
my-react-app/src/components/Header.js
rdb39d9e r8ca35dc 1 1 import React from 'react'; 2 import { Link } from 'react-router-dom';2 import { Link, useNavigate } from 'react-router-dom'; 3 3 4 4 const Header = () => { 5 const navigate = useNavigate(); 6 7 // Check if the user is logged in by looking for a token in localStorage 8 const isLoggedIn = localStorage.getItem('token'); 9 10 const handleLogout = () => { 11 // Clear the token from localStorage 12 localStorage.removeItem('token'); 13 // Redirect to the home page or login page after logging out 14 navigate('/login'); 15 }; 16 5 17 return ( 6 18 <header className="header navbar navbar-expand-lg navbar-light bg-light"> … … 15 27 </li> 16 28 <li className="nav-item"> 17 <Link className="nav-link" to="/customers">Customers</Link>18 </li>19 <li className="nav-item">20 <Link className="nav-link" to="/customers/add">Add Customer</Link>21 </li>22 <li className="nav-item">23 29 <Link className="nav-link" to="/restaurants">Restaurants</Link> 24 30 </li> … … 26 32 <Link className="nav-link" to="/reservations">Reservations</Link> 27 33 </li> 34 <li className="nav-item"> 35 <Link className="nav-link" to="/reservations-past">Reservation history</Link> 36 </li> 28 37 <form className="form-inline mt-2 mt-md-0 ml-3"> 29 <Link className="btn btn-outline-info my-2 my-sm-0" to={"/login"}>Login</Link> 38 {isLoggedIn ? ( 39 <button className="btn btn-outline-danger my-2 my-sm-0" onClick={handleLogout}>Logout</button> 40 ) : ( 41 <Link className="btn btn-outline-info my-2 my-sm-0" to="/login">Login</Link> 42 )} 30 43 </form> 31 44 </ul> -
my-react-app/src/components/Login.js
rdb39d9e r8ca35dc 6 6 const navigate = useNavigate(); 7 7 const [credentials, setCredentials] = useState({ username: '', password: '' }); 8 const [error, setError] = useState(''); 8 9 9 10 const handleChange = (e) => { … … 15 16 e.preventDefault(); 16 17 try { 17 const response = await axios.post('http://localhost:808 0/api/login', {18 const response = await axios.post('http://localhost:8081/api/login', { 18 19 email: credentials.username, 19 20 password: credentials.password 20 21 }); 21 22 const { token } = response.data; 22 // Store token securely (e.g., using HTTP cookies) 23 24 // Store token securely (consider httpOnly cookies) 23 25 localStorage.setItem('token', token); 24 26 … … 27 29 // Handle login failure 28 30 console.error('Login failed:', error); 31 setError('Login failed. Please check your credentials and try again.'); 29 32 } 30 33 }; 31 32 34 33 35 return ( … … 53 55 /> 54 56 </div> 57 {error && <div style={{ color: 'red' }}>{error}</div>} 55 58 <button type="submit">Login</button> 56 59 </form> -
my-react-app/src/components/LoginForm.js
rdb39d9e r8ca35dc 55 55 <div className="tab-content"> 56 56 <div 57 className={classNames("tab-pane", "fade", this.state.active === "login" ? "show active" : "")} id="pills-login"> 57 className={classNames("tab-pane", "fade", this.state.active === "login" ? "show active" : "")} 58 id="pills-login"> 58 59 <form onSubmit={this.onSubmitLogin}> 59 60 <div className="form-outline mb-4"> 60 <input type="email" id="email" name="email" className="form-control" onChange={this.onChangeHandler}/> 61 <input type="email" id="email" name="email" className="form-control" 62 onChange={this.onChangeHandler}/> 61 63 <label className="form-label" htmlFor="email">Email</label> 62 64 </div> 63 65 <div className="form-outline mb-4"> 64 <input type="password" id="loginPassword" name="password" className="form-control" onChange={this.onChangeHandler}/> 66 <input type="password" id="loginPassword" name="password" className="form-control" 67 onChange={this.onChangeHandler}/> 65 68 <label className="form-label" htmlFor="loginPassword">Password</label> 66 69 </div> … … 71 74 72 75 <div 73 className={classNames("tab-pane", "fade", this.state.active === "register" ? "show active" : "")} id="pills-register"> 76 className={classNames("tab-pane", "fade", this.state.active === "register" ? "show active" : "")} 77 id="pills-register"> 74 78 <form onSubmit={this.onSubmitRegister}> 75 79 <div className="form-outline mb-4"> 76 <input type="text" id="firstName" name="firstName" className="form-control" onChange={this.onChangeHandler}/> 80 <input type="text" id="firstName" name="firstName" className="form-control" 81 onChange={this.onChangeHandler}/> 77 82 <label className="form-label" htmlFor="firstName">First Name</label> 78 83 </div> 79 84 <div className="form-outline mb-4"> 80 <input type="text" id="lastName" name="lastName" className="form-control" onChange={this.onChangeHandler}/> 85 <input type="text" id="lastName" name="lastName" className="form-control" 86 onChange={this.onChangeHandler}/> 81 87 <label className="form-label" htmlFor="lastName">Last Name</label> 82 88 </div> 83 89 <div className="form-outline mb-4"> 84 <input type="text" id="email" name="email" className="form-control" onChange={this.onChangeHandler}/> 90 <input type="email" id="email" name="email" className="form-control" 91 onChange={this.onChangeHandler}/> 85 92 <label className="form-label" htmlFor="email">Email</label> 86 93 </div> 87 94 <div className="form-outline mb-4"> 88 <input type="password" id="loginPassword" name="password" className="form-control" onChange={this.onChangeHandler}/> 95 <input type="password" id="loginPassword" name="password" className="form-control" 96 onChange={this.onChangeHandler}/> 89 97 <label className="form-label" htmlFor="loginPassword">Password</label> 90 98 </div> 91 99 92 <button type="submit" className="btn btn-primary btn-block mb-4"> Sign In</button>100 <button type="submit" className="btn btn-primary btn-block mb-4">Register</button> 93 101 </form> 94 102 </div> … … 96 104 </div> 97 105 </div> 98 ) 106 ); 107 99 108 } 100 109 } -
my-react-app/src/components/MembershipsEnum.js
rdb39d9e r8ca35dc 3 3 4 4 const MembershipsEnum = () => { 5 const [memberships, setMemberships] = useState([]); 6 7 useEffect(() => { 8 const fetchMemberships = async () => { 9 try { 10 const response = await axios.get('http://localhost:8080/api/memberships'); 11 // Assuming the response.data is an array of enum values 12 setMemberships(response.data); 13 } catch (error) { 14 console.error('Error fetching enum data:', error); 15 } 16 }; 17 18 fetchMemberships(); 19 }, []); 20 21 return memberships; 5 return ['GOLD', 'PLATINUM', 'STANDARD']; 22 6 }; 23 7 -
my-react-app/src/components/ReservationConfirmation.js
rdb39d9e r8ca35dc 3 3 import axios from 'axios'; 4 4 import { useNavigate } from 'react-router-dom'; 5 import {jwtDecode} from "jwt-decode"; 5 6 6 7 const ReservationConfirmation = () => { … … 17 18 const fetchTableDetails = async () => { 18 19 try { 19 const tableResponse = await axios.get(`http://localhost:808 0/api/tables/${tableNumber}`);20 const tableResponse = await axios.get(`http://localhost:8081/api/tables/${tableNumber}`); 20 21 setTable(tableResponse.data); 21 22 22 const restaurantResponse = await axios.get(`http://localhost:808 0/api/restaurants/${restaurantId}`);23 const restaurantResponse = await axios.get(`http://localhost:8081/api/restaurants/${restaurantId}`); 23 24 setRestaurant(restaurantResponse.data); 24 25 } catch (error) { … … 31 32 const handleSubmit = async (e) => { 32 33 e.preventDefault(); 33 // Handle form submission here 34 35 if (!restaurant || !table) { 36 console.error("Restaurant or table is missing."); 37 return; 38 } 39 34 40 try { 35 // Check if restaurant and table are valid36 if (! restaurant || !table) {37 console.error(" Restaurant or table is missing.");41 const token = localStorage.getItem("token"); 42 if (!token) { 43 console.error("No token found"); 38 44 return; 39 45 } 40 46 41 const response = await axios.post(`http://localhost:8080/api/reservations`, { 42 restaurant: restaurant, // Assuming restaurant has an 'id' property 43 table: table, // Assuming table has an 'id' property 44 checkInTime: timeSlot, // Fill in as needed 45 partySize: partySize, 46 specialRequests: specialRequests 47 }); 48 // Handle successful reservation creation 49 // console.log("Reservation created:", response.data); 50 navigate("/reservations") 47 // Decode the token to get the user email 48 const decodedToken = jwtDecode(token); 49 console.log(decodedToken) 50 const userId = decodedToken.iss;// Assuming the email is part of the decoded JWT token 51 52 const response = await axios.post( 53 `http://localhost:8081/api/reservations/${userId}`, 54 { 55 restaurant: restaurant, 56 table: table, 57 checkInTime: timeSlot, 58 partySize: partySize, 59 specialRequests: specialRequests 60 }, 61 { 62 headers: { 63 Authorization: `Bearer ${token}` // Include the token here 64 } 65 } 66 ); 67 68 navigate("/reservations"); 51 69 } catch (error) { 52 70 console.error("Error creating reservation:", error); -
my-react-app/src/components/ReservationEdit.js
rdb39d9e r8ca35dc 3 3 import {useNavigate, useParams} from 'react-router-dom'; 4 4 import StarRating from "./StarRating"; 5 import {jwtDecode} from "jwt-decode"; 5 6 6 7 const ReservationEdit = () => { … … 14 15 const [timeSlots, setTimeSlots] = useState([]); 15 16 const [filteredTimeSlots, setFilteredTimeSlots] = useState([]); 17 const [checkInTime, setCheckInTime] = useState([]); 16 18 17 19 useEffect(() => { … … 19 21 try { 20 22 setIsLoading(true); 21 const response = await axios.get(`http://localhost:8080/api/reservations/${reservationId}`); 22 setFormData(response.data); // Set form data with reservation data 23 const response = await axios.get(`http://localhost:8081/api/reservations/${reservationId}`); 24 setCheckInTime(response.data.checkInTime) 25 setFormData(response.data); 23 26 setTable(response.data.table); 24 27 setRestaurant(response.data.restaurant); … … 56 59 const handleSubmit = async (e) => { 57 60 e.preventDefault(); 61 58 62 try { 59 // Send updated reservation data to the server 60 await axios.post(`http://localhost:8080/api/reservations/${reservationId}`, formData); 61 // Redirect or show success message 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 62 75 navigate(`/reservations`) 63 76 } catch (error) { … … 71 84 const formattedTime = date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }); 72 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}`; 73 93 }; 74 94 … … 100 120 ))} 101 121 </select> 122 <label className=".text-danger">Current check in time: {formatTimeSlot(checkInTime)}</label> 102 123 </div> 103 124 <div className="mb-3"> -
my-react-app/src/components/Reservations.js
rdb39d9e r8ca35dc 3 3 import 'bootstrap/dist/css/bootstrap.min.css'; 4 4 import {useNavigate} from "react-router-dom"; 5 import {jwtDecode} from "jwt-decode"; 5 6 6 7 … … 13 14 const fetchReservations = async () => { 14 15 try { 15 const response = await axios.get('http://localhost:8080/api/reservations'); // Adjust URL as needed 16 const token = localStorage.getItem("token"); 17 if (!token) { 18 console.error("No token found"); 19 return; 20 } 21 const decodedToken = jwtDecode(token); 22 console.log(decodedToken) 23 const userId = decodedToken.iss; 24 25 const response = await axios.get(`http://localhost:8081/api/reservations/by/${userId}`); 16 26 setReservations(response.data); 17 27 } catch (error) { … … 31 41 const handleCancelReservation = async (reservationID) => { 32 42 try { 33 await axios.delete(`http://localhost:808 0/api/reservations/delete/${reservationID}`);43 await axios.delete(`http://localhost:8081/api/reservations/delete/${reservationID}`); 34 44 setReservations(reservations.filter(reservation => reservation.reservationID !== reservationID)); 35 45 alert('Reservation canceled successfully!'); -
my-react-app/src/components/RestaurantContext.js
rdb39d9e r8ca35dc 10 10 const fetchRestaurants = async () => { 11 11 try { 12 const response = await axios.get('http://localhost:808 0/api/restaurants');12 const response = await axios.get('http://localhost:8081/api/restaurants'); 13 13 setRestaurants(response.data); 14 14 } catch (error) { … … 17 17 }; 18 18 19 fetchRestaurants() ;19 fetchRestaurants().then(r => console.log(fetchRestaurants())); 20 20 }, []); 21 21 -
my-react-app/src/components/RestaurantDetails.js
rdb39d9e r8ca35dc 21 21 try { 22 22 if (!id) return; 23 const response = await axios.get(`http://localhost:808 0/api/restaurants/${id}`);23 const response = await axios.get(`http://localhost:8081/api/restaurants/${id}`); 24 24 setRestaurant(response.data); 25 25 } catch (error) { … … 36 36 const fetchTableDetails = async () => { 37 37 try { 38 const response = await axios.get(`http://localhost:808 0/api/tables/${selectedTableId}`);38 const response = await axios.get(`http://localhost:8081/api/tables/${selectedTableId}`); 39 39 setSelectedTable(response.data); 40 40 } catch (error) {
Note:
See TracChangeset
for help on using the changeset viewer.