Skip to content

Commit

Permalink
feat: actually extract hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
KevinWu098 committed Jul 22, 2024
1 parent 0b6710d commit dcda74d
Show file tree
Hide file tree
Showing 2 changed files with 93 additions and 0 deletions.
47 changes: 47 additions & 0 deletions src/app/pages/Events/useEvents.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { useState, useEffect, useCallback } from "react";
import { parseEvents, joinEvents } from "./utils.js";
import EVENT_DATA from "assets/data/events/all.json";
import { client } from "sanity-client.js";

const legacyEvents = parseEvents(EVENT_DATA); // events from manual JSON file

export const useEvents = () => {
const [events, setEvents] = useState([]);

const fetchEvents = useCallback(async () => {
const result = await client.fetch(
`*[_type == "event"] | order(time desc)`,
{},
);
return result.map((item) => ({
title: item.title,
time: item.time,
duration: item.duration,
type: item.type,
desc: item.desc,
place: item.place,
links: item.links
? item.links.map((linkItem) => ({
label: linkItem.label,
link: linkItem.link,
}))
: [],
}));
}, []);

useEffect(() => {
const getEvents = async () => {
try {
const data = await fetchEvents();
const eventData = parseEvents(data);
const joinedEvents = joinEvents(eventData, legacyEvents);
setEvents(joinedEvents);
} catch (e) {
console.error(e);
}
};
getEvents();
}, [fetchEvents, legacyEvents]);

return events;
};
46 changes: 46 additions & 0 deletions src/app/pages/Events/utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
export const parseEvents = (events) => {
let eventData = {
upcoming: [],
past: [],
};

const now = new Date();

for (let event of events) {
const eventTime = new Date(
new Date(event.time).getTime() + event.duration * 60000,
);

if (now < eventTime) {
eventData.upcoming.unshift(event);
} else {
eventData.past.push(event);
}
}

return eventData;
};

export const joinEvents = (a, b) => {
// handle uninitialized/unparsed event lists
a = a.upcoming && a.past ? a : { upcoming: [], past: [] };
b = b.upcoming && b.past ? b : { upcoming: [], past: [] };

const combinedUpcoming = [...a.upcoming, ...b.upcoming];
const combinedPast = [...a.past, ...b.past];

let nextEvent = null;

if (combinedUpcoming.length > 0) {
combinedUpcoming.sort(
(e1, e2) => new Date(e1.time) - new Date(e2.time),
);
nextEvent = combinedUpcoming.at(0) ?? null;
}

return {
upcoming: combinedUpcoming,
past: combinedPast,
next: nextEvent,
};
};

0 comments on commit dcda74d

Please sign in to comment.