Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP Pagination #20

Draft
wants to merge 5 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"workbench.colorCustomizations": {
"titleBar.activeForeground": "#FFF",
"titleBar.inactiveForeground": "#FFF",
"titleBar.activeBackground": "#7D5EBF",
"titleBar.inactiveBackground": "#580259"

}
45 changes: 45 additions & 0 deletions components/Pagination.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
export default function Pagination({ page, limit, totalPlaces, onPageChange }) {
const numberOfPages = Math.ceil(totalPlaces / limit);

const pageNumbers = [];

for (let i = 1; i <= numberOfPages; i++) {
pageNumbers.push(i);
}

return (
<div className='flex flex-wrap flex-row justify-center space-x-2'>
{page > 1 && (
<div
onClick={() => onPageChange(page - 1)}
className='bg-purple-500 border-2 border-purple-500 mb-2 text-white font-bold py-2 px-4 rounded cursor-pointer'
>
Previous
</div>
)}

{pageNumbers.map((number) => (
<div
key={number}
onClick={() => onPageChange(number)}
className={`bg-purple-500 border-2 border-purple-500 mb-2 text-white font-bold py-2 px-4 rounded cursor-pointer ${
number === page
? "bg-transparent border-purple-300 text-purple-300"
: ""
}`}
>
{number}
</div>
))}

{page < numberOfPages && (
<div
onClick={() => onPageChange(page + 1)}
className='bg-purple-500 border-2 border-purple-500 mb-2 text-white font-bold py-2 px-4 rounded cursor-pointer'
>
Next
</div>
)}
</div>
);
}
23 changes: 23 additions & 0 deletions components/TotalHappyHours.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
export default function determineCurrentHappyHourVerbiage(happyHoursRightNow) {
if (happyHoursRightNow > 1) {
const multiplePhrases = [
`There are ${happyHoursRightNow} happy hours happening right now. Get on it!`,
`You've got options! ${happyHoursRightNow} happy hours are happening right now.`,
`Hurry! ${happyHoursRightNow} happy hours are currently going on.`,
`Don't miss out! ${happyHoursRightNow} happy hours are happening as we speak.`,
`${happyHoursRightNow} happy hours are on right now! It's a good time to go out.`,
];
return multiplePhrases[Math.floor(Math.random() * multiplePhrases.length)];
}

if (happyHoursRightNow === 1) {
const singlePhrases = [
`There's only one happy hour happening right now. Don't miss it!`,
`Just one happy hour going on at the moment. Better hurry!`,
`One happy hour is happening right now. It's the place to be!`,
];
return singlePhrases[Math.floor(Math.random() * singlePhrases.length)];
}

return `There are ${happyHoursRightNow} happy hours happening right now.`;
}
25 changes: 24 additions & 1 deletion pages/api/places/[day].js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@ import { convertDayName } from "../../../lib/date";

export default async function handler(req, res) {
let dayOfWeek = convertDayName(req.query.day);
const { page = 1, limit = 10, currentTime } = req.query;

const pageNumber = parseInt(page, 10);
const pageSize = parseInt(limit, 10);
const currentTimeInt = parseInt(currentTime, 10);

try {
let { db } = await connectToDatabase();
Expand Down Expand Up @@ -58,12 +63,30 @@ export default async function handler(req, res) {
},
},
{
$sort: { featured: -1 },
$sort: { featured: -1 }, // Sort by featured descending
},
{
$skip: (pageNumber - 1) * pageSize,
},
{
$limit: pageSize,
},
])
.toArray();

const totalPlaces = await db.collection("places").countDocuments({
enabled: true,
events: {
$elemMatch: {
keywords: "happyHour",
"eventSchedule.byDay": dayOfWeek,
},
},
});

return res.json({
places: JSON.parse(JSON.stringify(places)),
totalPlaces,
success: true,
});
} catch (error) {
Expand Down
72 changes: 23 additions & 49 deletions pages/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,24 +8,23 @@ import { getDay } from "../lib/date";
import fetcher from "../lib/fetcher";

import Navigation from "../components/Navigation";
import Pagination from "../components/Pagination";
import Loader from "../components/Loader";
import { hasActiveHappyHour, isCurrentlyBetweenTwoTimes } from "../lib/time";
import { getCurrentTime, hasActiveHappyHour } from "../lib/time";
import {
sortByDistance,
calculateDistance,
getUserLocation,
} from "../lib/location";
import determineCurrentHappyHourVerbiage from "../components/TotalHappyHours";
import { useEffect } from "react";

function Home() {
const [amountOfPlaces, setAmountOfPlaces] = useState(10);
const [page, setPage] = useState(1);
const [limit, setLimit] = useState(10);
const [userLocation, setUserLocation] = useState(null);
const day = getDay();

function showMorePlaces() {
setAmountOfPlaces(amountOfPlaces + 10);
}

useEffect(() => {
const fetchUserLocation = async () => {
try {
Expand All @@ -50,11 +49,19 @@ function Home() {
fetchUserLocation();
}, []);

const { data, error } = useSWR("/api/places/" + day, fetcher);
const handlePageChange = (newPage) => {
setPage(newPage);
};

const { data, error } = useSWR(
`/api/places/${day}?page=${page}&limit=${limit}&currentTime=${getCurrentTime()}`,
fetcher
);
if (error) return <div>Failed to load</div>;
if (!data) return <Loader />;
if (!data.success) return <div>Failed to load</div>;
let places = data.places;
let totalPlaces = data.totalPlaces;

// sort by distance
if (userLocation) {
Expand All @@ -73,66 +80,33 @@ function Home() {
places = [...activeSpecialsPlaces, ...otherPlaces];

function happyHoursRightNow() {
const currentTime = new Date();
const currentDay = currentTime.getDay();

const todayPlace = places.filter(
(place) => hasActiveHappyHour(place, day)
);
const todayPlace = places.filter((place) => hasActiveHappyHour(place, day));

return todayPlace.length;
}

function determineCurrentHappyHourVerbiage() {
if (happyHoursRightNow() > 1)
return `There are ${happyHoursRightNow()} happy hours happening right now. Get on
it!`;
if (happyHoursRightNow() === 1)
return `There's only ${happyHoursRightNow()} happy hour happening right now. Get on
it!`;

return `There are ${happyHoursRightNow()} happy hours happening right now.`;
}

const bars = places.slice(0, amountOfPlaces);

return (
<div>
<Meta />
<Header title={`${day} Specials`} />
<div className='flex flex-col items-center'>
<div className='flex flex-col md:w-1/2'>
<div className='mt-6 mx-10 text-center'>
{determineCurrentHappyHourVerbiage()}
{determineCurrentHappyHourVerbiage(happyHoursRightNow())}
</div>
<SearchBar />
<Navigation />
<main>
<div className='flex flex-wrap justify-items-center mt-6'>
{/* {daysOfTheWeek.map((theDay) => (
<button
className='w-1/5 px-4'
onClick={() => setNavigationDay(theDay)}
key={theDay}
>
{theDay}
</button>
))} */}
</div>
<div className='flex flex-wrap w-full'>
{bars.map((bar) => (
{places.map((bar) => (
<Place place={bar} day={day} key={bar._id} />
))}
{places.length <= amountOfPlaces ? null : (
<div className='flex justify-center w-full'>
<button
className='w-1/2 bg-purple-500 text-white font-bold py-2 px-4 rounded'
onClick={showMorePlaces}
>
See More
</button>
</div>
)}
<Pagination
page={page}
limit={limit}
totalPlaces={totalPlaces}
onPageChange={handlePageChange}
/>
</div>
</main>
</div>
Expand Down