Skip to content

Commit

Permalink
use events store in manage events page
Browse files Browse the repository at this point in the history
  • Loading branch information
juancwu committed May 17, 2024
1 parent 52f4575 commit b638417
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
16 changes: 13 additions & 3 deletions src/pages/admin/ManageEvents.page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,16 @@ import { FormEventHandler, useEffect, useRef, useState } from "react";
import { nanoid } from "nanoid";
import { firestore } from "@/services/firebase";
import { z } from "zod";
import { useEventsStore } from "@/stores/events.store";
import { useShallow } from "zustand/react/shallow";

type KeyOfEventItem = keyof EventItem;

export const AdminManageEventsPage = () => {
const [events, setEvents] = useState<EventItem[]>([]);
const events = useEventsStore(useShallow((state) => state.events));
const setEvents = useEventsStore((state) => state.setEvents);
const addEvent = useEventsStore((state) => state.addEvent);
const removeEvent = useEventsStore((state) => state.removeEvent);
const [isLoading, setIsLoading] = useState(true);
const { showNotification } = useNotification();
const [newEvent, setNewEvent] = useState<EventItem>({
Expand All @@ -33,6 +38,11 @@ export const AdminManageEventsPage = () => {
const timeoutRef = useRef<number | null>(null);

useEffect(() => {
if (events.length > 0) {
setIsLoading(false);
return;
}

const timeout = 5000; // 5 seconds
if (timeoutRef.current) window.clearTimeout(timeoutRef.current);
timeoutRef.current = window.setTimeout(() => {
Expand Down Expand Up @@ -106,7 +116,7 @@ export const AdminManageEventsPage = () => {
});

if (!isEditingEvent) {
setEvents([...events, newEvent]);
addEvent(newEvent);
}
} catch (e) {
console.error(e);
Expand Down Expand Up @@ -139,7 +149,7 @@ export const AdminManageEventsPage = () => {
const handleDeleteEvent = async (id: string) => {
try {
await deleteDoc(doc(firestore, "events", id));
setEvents(events.filter((evt) => evt.id !== id));
removeEvent(id);
showNotification({
title: "Event Deleted",
message: "",
Expand Down
6 changes: 6 additions & 0 deletions src/stores/events.store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { create } from "zustand";
export interface EventStore {
events: EventItem[];
addEvent: (event: EventItem) => void;
removeEvent: (id: string) => void;
setEvents: (events: EventItem[]) => void;
}

Expand All @@ -14,6 +15,11 @@ export const useEventsStore = create<EventStore>((set) => ({
state.events.push(event);
return state;
}),
removeEvent: (id: string) =>
set((state) => {
state.events = state.events.filter((evt) => evt.id !== id);
return state;
}),
setEvents: (events: EventItem[]) =>
set((state) => {
state.events = events;
Expand Down

0 comments on commit b638417

Please sign in to comment.