|
| 1 | +import { useEffect, useState } from "react"; |
| 2 | +import Loading from "./Loading"; |
| 3 | +import Tour from "./Tour"; |
| 4 | + |
| 5 | +const url = "https://course-api.com/react-tours-project"; |
| 6 | + |
| 7 | +const backgroundClass = "bg-blue-50 min-h-screen py-14 px-10"; |
| 8 | + |
| 9 | +export default function Tours() { |
| 10 | + const [dataTours, setDataTours] = useState([]); |
| 11 | + const [loading, setLoading] = useState(false); |
| 12 | + |
| 13 | + const handleDelete = (id) => { |
| 14 | + const data = dataTours.filter((item) => item.id !== id); |
| 15 | + setDataTours(data); |
| 16 | + }; |
| 17 | + const fetchTours = async () => { |
| 18 | + setLoading(true); |
| 19 | + try { |
| 20 | + const res = await fetch(url); |
| 21 | + const data = await res.json(); |
| 22 | + setDataTours(data); |
| 23 | + setLoading(false); |
| 24 | + console.log("data", data); |
| 25 | + |
| 26 | + return data; |
| 27 | + } catch (error) { |
| 28 | + console.error(error.message); |
| 29 | + setLoading(false); |
| 30 | + } |
| 31 | + }; |
| 32 | + |
| 33 | + useEffect(() => { |
| 34 | + fetchTours(); |
| 35 | + }, []); |
| 36 | + |
| 37 | + if (loading) return <Loading />; |
| 38 | + |
| 39 | + if (dataTours.length === 0) |
| 40 | + return ( |
| 41 | + <div className={backgroundClass}> |
| 42 | + <div className="my-20 mx-auto w-52"> |
| 43 | + <p className="text-3xl font-bold text-gray-800 mb-4">No Tours Left</p> |
| 44 | + <button |
| 45 | + className="p-1 rounded-md text-white bg-blue-400 font-bold cursor-pointer" |
| 46 | + onClick={fetchTours} |
| 47 | + > |
| 48 | + Refresh |
| 49 | + </button> |
| 50 | + </div> |
| 51 | + </div> |
| 52 | + ); |
| 53 | + |
| 54 | + return ( |
| 55 | + <div className={backgroundClass}> |
| 56 | + <h1 className="text-gray-800 text-4xl font-bold text-center mb-20 relative before:content-[''] before:absolute before:-bottom-4 before:left-0 before:right-0 before:mx-auto before:w-1/10 before:h-1 before:bg-blue-400"> |
| 57 | + Our Tours |
| 58 | + </h1> |
| 59 | + <div className="grid grid-cols-3 gap-5"> |
| 60 | + {dataTours.map((tour) => ( |
| 61 | + <Tour key={tour.id} {...tour} handleDelete={handleDelete} /> |
| 62 | + ))} |
| 63 | + </div> |
| 64 | + </div> |
| 65 | + ); |
| 66 | +} |
0 commit comments