ajout authentification admin/user
This commit is contained in:
@@ -1,14 +1,35 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useParams, Link } from 'react-router-dom';
|
||||
import { getBookById } from '../api/books';
|
||||
import { getBookById, reserveBook } from '../api/books';
|
||||
import { useAuth } from '../context/AuthContext';
|
||||
|
||||
export default function BookDetail() {
|
||||
const { bookId } = useParams();
|
||||
const { user } = useAuth();
|
||||
const { bookId } = useParams();
|
||||
const [book, setBook] = useState(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState(null);
|
||||
const [phoneNumber, setPhoneNumber] = useState('');
|
||||
const [reservationStatus, setReservationStatus] = useState(null);
|
||||
const [reserving, setReserving] = useState(false);
|
||||
|
||||
useEffect(() => {getBookById(bookId).then((response) => setBook(response.data)).catch((err) => {console.error(err);setError('Livre introuvable.');}).finally(() => setLoading(false));}, [bookId]);
|
||||
useEffect(() => { getBookById(bookId).then((response) => setBook(response.data)).catch((err) => { console.error(err); setError('Livre introuvable.'); }).finally(() => setLoading(false)); }, [bookId]);
|
||||
|
||||
function handleReservation(e) {
|
||||
e.preventDefault();
|
||||
setReserving(true);
|
||||
setReservationStatus(null);
|
||||
reserveBook(bookId, { phoneNumber })
|
||||
.then(() => {
|
||||
setReservationStatus({ success: true, message: 'Réservation effectuée avec succès !' });
|
||||
setPhoneNumber('');
|
||||
})
|
||||
.catch((err) => {
|
||||
const msg = err.response?.data || 'Erreur lors de la réservation.';
|
||||
setReservationStatus({ success: false, message: msg });
|
||||
})
|
||||
.finally(() => setReserving(false));
|
||||
}
|
||||
|
||||
if (loading) return <main><p>Chargement…</p></main>;
|
||||
if (error) return <main><p>{error}</p><Link to="/books">← Retour au catalogue</Link></main>;
|
||||
@@ -26,6 +47,30 @@ export default function BookDetail() {
|
||||
<p>Langue : {book.language}</p>
|
||||
<p>Catégories : {book.categories?.join(', ')}</p>
|
||||
{book.description && <p>{book.description}</p>}
|
||||
|
||||
{user?.role === 'user' && <section>
|
||||
<h2>Réserver ce livre</h2>
|
||||
<form onSubmit={handleReservation}>
|
||||
<label>
|
||||
Numéro de téléphone :
|
||||
<input
|
||||
type="tel"
|
||||
value={phoneNumber}
|
||||
onChange={(e) => setPhoneNumber(e.target.value)}
|
||||
placeholder="0612345678"
|
||||
required
|
||||
/>
|
||||
</label>
|
||||
<button type="submit" disabled={reserving}>
|
||||
{reserving ? 'Réservation…' : 'Réserver'}
|
||||
</button>
|
||||
</form>
|
||||
{reservationStatus && (
|
||||
<p style={{ color: reservationStatus.success ? 'green' : 'red' }}>
|
||||
{reservationStatus.message}
|
||||
</p>
|
||||
)}
|
||||
</section>}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user