Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
4.2 kB
1
Indexable
Never
// BreweryDetails.jsx
import React, { useState, useEffect } from 'react';
import axios from 'axios';

const BreweryDetails = ({ match }) => {
    const [brewery, setBrewery] = useState(null);
    const [reviews, setReviews] = useState([]);
    const [newRating, setNewRating] = useState(0);
    const [newDescription, setNewDescription] = useState('');
    const [error, setError] = useState('');

    useEffect(() => {
        // Fetch brewery details and reviews when component mounts
        const fetchBreweryDetails = async () => {
            try {
                const response = await axios.get(`/api/breweries/${match.params.id}`);
                setBrewery(response.data);
                setReviews(response.data.reviews); // Assuming reviews are nested within brewery data
            } catch (error) {
                console.error('Error fetching brewery details:', error);
                setError('Error fetching brewery details');
            }
        };

        fetchBreweryDetails();
    }, [match.params.id]);

    const handleAddReview = async () => {
        try {
            const response = await axios.post(`/api/breweries/${match.params.id}/reviews`, {
                rating: newRating,
                description: newDescription
            });
            console.log(response.data); // Handle success message
            // Update reviews state to include the new review
            setReviews([...reviews, response.data]);
            // Reset form fields
            setNewRating(0);
            setNewDescription('');
        } catch (error) {
            console.error('Error adding review:', error);
            setError('Error adding review');
        }
    };

    if (!brewery) {
        return <div>Loading...</div>; // Add loading state if brewery details are still fetching
    }

    return (
        <div className="container">
            <h2 className="my-4">{brewery.name}</h2>
            <div>
                <p><strong>Address:</strong> {brewery.address}</p>
                <p><strong>Phone:</strong> {brewery.phone}</p>
                <p><strong>Website:</strong> <a href={brewery.website_url} target="_blank" rel="noopener noreferrer">{brewery.website_url}</a></p>
                <p><strong>Rating:</strong> {calculateAverageRating(reviews)}</p>
                <p><strong>State, City:</strong> {brewery.state}, {brewery.city}</p>
            </div>

            <h3 className="my-4">Reviews</h3>
            {reviews.length === 0 ? <p>No reviews yet.</p> : (
                <ul className="list-group">
                    {reviews.map((review, index) => (
                        <li key={index} className="list-group-item">
                            <p><strong>Rating:</strong> {review.rating}</p>
                            <p><strong>Description:</strong> {review.description}</p>
                        </li>
                    ))}
                </ul>
            )}

            <h3 className="my-4">Add a Review</h3>
            <form onSubmit={handleAddReview}>
                <div className="mb-3">
                    <label htmlFor="rating" className="form-label">Rating (1-5)</label>
                    <input type="number" className="form-control" id="rating" min="1" max="5" value={newRating} onChange={(e) => setNewRating(parseInt(e.target.value))} />
                </div>
                <div className="mb-3">
                    <label htmlFor="description" className="form-label">Description</label>
                    <textarea className="form-control" id="description" value={newDescription} onChange={(e) => setNewDescription(e.target.value)} />
                </div>
                {error && <div className="alert alert-danger">{error}</div>}
                <button type="submit" className="btn btn-primary">Submit Review</button>
            </form>
        </div>
    );
};

export default BreweryDetails;

// Helper function to calculate average rating
const calculateAverageRating = (reviews) => {
    if (reviews.length === 0) return 'N/A';
    const totalRating = reviews.reduce((acc, curr) => acc + curr.rating, 0);
    return (totalRating / reviews.length).toFixed(1);
};
Leave a Comment