hosting: fix notification on reserve
This commit is contained in:
parent
13ae6c6942
commit
8771e859fd
81
frontend/src/NotificationContext.tsx
Normal file
81
frontend/src/NotificationContext.tsx
Normal file
@ -0,0 +1,81 @@
|
||||
// src/NotificationContext.tsx
|
||||
|
||||
import React, { createContext, useContext, useState } from 'react';
|
||||
|
||||
type NotificationType = 'success' | 'error';
|
||||
|
||||
interface NotificationContextType {
|
||||
notify: (message: string, type: NotificationType) => void;
|
||||
}
|
||||
|
||||
const NotificationContext = createContext<NotificationContextType | undefined>(undefined);
|
||||
|
||||
export const NotificationProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
||||
const [notification, setNotification] = useState<string | null>(null);
|
||||
const [notificationType, setNotificationType] = useState<NotificationType | null>(null);
|
||||
|
||||
const notify = (message: string, type: NotificationType) => {
|
||||
setNotification(message);
|
||||
setNotificationType(type);
|
||||
|
||||
// Automatically dismiss notification after 3 seconds
|
||||
setTimeout(() => {
|
||||
setNotification(null);
|
||||
setNotificationType(null);
|
||||
}, 3000);
|
||||
};
|
||||
|
||||
return (
|
||||
<NotificationContext.Provider value={{ notify }}>
|
||||
{children}
|
||||
{notification && (
|
||||
<Notification message={notification} onClose={() => setNotification(null)} type={notificationType!} />
|
||||
)}
|
||||
</NotificationContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export const useNotification = () => {
|
||||
const context = useContext(NotificationContext);
|
||||
if (!context) {
|
||||
throw new Error('useNotification must be used within a NotificationProvider');
|
||||
}
|
||||
return context.notify;
|
||||
};
|
||||
|
||||
|
||||
interface NotificationProps {
|
||||
message: string;
|
||||
onClose: () => void;
|
||||
type: 'success' | 'error'; // Define notification types
|
||||
}
|
||||
|
||||
// Notification Component
|
||||
const Notification: React.FC<NotificationProps> = ({ message, onClose, type }) => {
|
||||
return (
|
||||
<div style={{ ...styles.notification, backgroundColor: type === 'success' ? '#4caf50' : '#f44336' }}>
|
||||
<p>{message}</p>
|
||||
<button onClick={onClose} style={styles.closeButton}>X</button>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// Notification styles remain the same...
|
||||
const styles: { [key: string]: React.CSSProperties } = {
|
||||
notification: {
|
||||
position: 'fixed',
|
||||
top: '20px',
|
||||
right: '20px',
|
||||
color: 'white',
|
||||
padding: '15px',
|
||||
borderRadius: '5px',
|
||||
zIndex: 1000,
|
||||
},
|
||||
closeButton: {
|
||||
background: 'transparent',
|
||||
border: 'none',
|
||||
color: 'white',
|
||||
cursor: 'pointer',
|
||||
marginLeft: '10px',
|
||||
},
|
||||
};
|
||||
@ -1,5 +1,6 @@
|
||||
import { useState } from "react";
|
||||
import useFetchHosting from "../utils/fetchHosting";
|
||||
import { useNotification } from "../NotificationContext";
|
||||
|
||||
|
||||
interface ReserveButtonProps {
|
||||
@ -10,12 +11,21 @@ interface ReserveButtonProps {
|
||||
|
||||
const ReserveButton: React.FC<ReserveButtonProps> = (props) => {
|
||||
const { reservedBy, update, id } = props;
|
||||
const [name, setName] = useState(reservedBy);
|
||||
const [name, setName] = useState(reservedBy || ''); // Default to empty if not reserved
|
||||
const isReserved = reservedBy !== '';
|
||||
const notify = useNotification();
|
||||
|
||||
const handleReserve = async () => {
|
||||
if (name.trim()) {
|
||||
await update(name, id); // Call the update function from props with the name and id
|
||||
if (!name.trim()) {
|
||||
notify('Поле имени не может быть пустым', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await update(name, id); // Await the update call
|
||||
notify(`Успешно забронировано для ${name}`, 'success'); // Move success notification here
|
||||
} catch (error) {
|
||||
notify(`Не удалось забронировать: ${error instanceof Error ? error.message : 'Unknown error'}`, 'error');
|
||||
}
|
||||
};
|
||||
|
||||
@ -26,7 +36,7 @@ const ReserveButton: React.FC<ReserveButtonProps> = (props) => {
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
placeholder="Введите ваше имя"
|
||||
disabled={isReserved} // Disable if already reserved
|
||||
disabled={isReserved} // Disable input if already reserved
|
||||
/>
|
||||
<button onClick={handleReserve} disabled={isReserved}>
|
||||
{isReserved ? 'Занято' : 'Занять'}
|
||||
|
||||
@ -2,9 +2,10 @@ import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import './index.css'
|
||||
import App from './App.tsx'
|
||||
import { NotificationProvider } from './NotificationContext.tsx'
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
<NotificationProvider><App/></NotificationProvider>
|
||||
</StrictMode>,
|
||||
)
|
||||
|
||||
@ -28,14 +28,12 @@ const useFetchHosting = () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const response = await fetch('https://example.backend.com/hosting');
|
||||
if (!response.ok) {
|
||||
const response = await fetch('/hosting');
|
||||
if (response.status != 200) {
|
||||
throw new Error('Network response was not ok');
|
||||
}
|
||||
const result = await response.json();
|
||||
setData(result);
|
||||
} catch (error) {
|
||||
setError(error instanceof Error ? error.message : 'Unknown error');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
@ -45,7 +43,7 @@ const useFetchHosting = () => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
try {
|
||||
const response = await fetch(`https://example.backend.com/hosting/${id}`, {
|
||||
const response = await fetch(`/hosting/${id}`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
@ -53,19 +51,19 @@ const useFetchHosting = () => {
|
||||
body: JSON.stringify({ reservedBy: name })
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Network response was not ok');
|
||||
if (!response.ok) { // Check for non-200 responses
|
||||
const errorText = await response.text(); // Capture the response text for further insights
|
||||
throw new Error(`Error ${response.status}: ${errorText}`);
|
||||
}
|
||||
|
||||
// Optional: Fetch the updated data after reservation
|
||||
await fetchData();
|
||||
} catch (error) {
|
||||
setError(error instanceof Error ? error.message : 'Unknown error');
|
||||
await fetchData();
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
useEffect(() => {
|
||||
//fetchData(); // Initial fetch on mount
|
||||
}, []);
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user