Skip to content

Commit

Permalink
fix: events and organization persist removed.
Browse files Browse the repository at this point in the history
  • Loading branch information
ZL-Asica committed Dec 6, 2024
1 parent 219b2e6 commit 44ba14f
Show file tree
Hide file tree
Showing 5 changed files with 125 additions and 138 deletions.
7 changes: 5 additions & 2 deletions src/components/Schedule/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,21 @@ import dayjs from 'dayjs';

import EventsCalendar from './EventsCalendar';

import { useEventStore } from '@/stores';

import {
generateICSFile,
generateCombinedICSFile,
} from '@/utils/generateICSFile';

interface ScheduleBaseProps {
events: DonationEvent[];
title: string;
description: string;
}

const ScheduleBase = ({ events, title, description }: ScheduleBaseProps) => {
const ScheduleBase = ({ title, description }: ScheduleBaseProps) => {
const events = useEventStore((store) => store.events);

const [selectedDate, setSelectedDate] = useState<Dayjs | null>(dayjs());
const [selectedEvent, setSelectedEvent] = useState<DonationEvent | null>(
null
Expand Down
5 changes: 1 addition & 4 deletions src/pages/Schedule.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useUserStore, useEventStore } from '@/stores';
import { useUserStore } from '@/stores';

import ScheduleBase from '@/components/Schedule';

Expand All @@ -7,8 +7,6 @@ const DonorSchedule = () => {

if (!user) return null;

const events = useEventStore((store) => store.events);

const title =
user.role === 'donor'
? 'Your Donation Schedule'
Expand All @@ -20,7 +18,6 @@ const DonorSchedule = () => {

return (
<ScheduleBase
events={events}
title={title}
description={description}
/>
Expand Down
137 changes: 64 additions & 73 deletions src/stores/eventStore.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { create } from 'zustand';
import { createJSONStorage, persist } from 'zustand/middleware';
import { collection, getDocs } from 'firebase/firestore';

import useUserStore from './userStore';
Expand All @@ -17,78 +16,70 @@ interface EventState {
) => Promise<void>;
}

const useEventStore = create<EventState>()(
persist(
(set, get) => ({
events: [],

setEvents: (events) => set({ events }),

fetchEventsByIds: async (eventIds: string[]) => {
if (!eventIds?.length) {
console.info('No event IDs provided.');
return;
}

try {
const eventsCollection = collection(db, 'events');
const snapshot = await getDocs(eventsCollection);

if (!snapshot.docs?.length) {
console.info('No events found in the collection.');
return;
}

const events: DonationEvent[] = snapshot.docs
.filter((doc) => eventIds.includes(doc.id))
.map((doc) => ({
...doc.data(),
eventId: doc.id,
})) as DonationEvent[];

set({ events });
} catch (error) {
console.error('Error fetching events by IDs:', error);
throw error;
}
},

addDonationEvent: async (
event,
donorUpdates,
organizationUpdates
): Promise<void> => {
try {
if (organizationUpdates.uid) {
await updateDocument(
'organization',
organizationUpdates.uid,
organizationUpdates
);
}

if (donorUpdates.uid) {
const userStore = useUserStore.getState();
await userStore.updateProfile(donorUpdates);
}

await updateEvent(event);

const currentEvents = get().events;
set({ events: [...currentEvents, event] });

console.info(`Donation event ${event.eventId} created successfully.`);
} catch (error) {
console.error('Error adding donation event:', error);
throw new Error('Failed to create donation event.');
}
},
}),
{
name: 'event-store',
storage: createJSONStorage(() => sessionStorage),
const useEventStore = create<EventState>()((set, get) => ({
events: [],

setEvents: (events) => set({ events }),

fetchEventsByIds: async (eventIds: string[]) => {
if (!eventIds?.length) {
console.info('No event IDs provided.');
return;
}

try {
const eventsCollection = collection(db, 'events');
const snapshot = await getDocs(eventsCollection);

if (!snapshot.docs?.length) {
console.info('No events found in the collection.');
return;
}

const events: DonationEvent[] = snapshot.docs
.filter((doc) => eventIds.includes(doc.id))
.map((doc) => ({
...doc.data(),
eventId: doc.id,
})) as DonationEvent[];

set({ events });
} catch (error) {
console.error('Error fetching events by IDs:', error);
throw error;
}
},

addDonationEvent: async (
event,
donorUpdates,
organizationUpdates
): Promise<void> => {
try {
if (organizationUpdates.uid) {
await updateDocument(
'organization',
organizationUpdates.uid,
organizationUpdates
);
}

if (donorUpdates.uid) {
const userStore = useUserStore.getState();
await userStore.updateProfile(donorUpdates);
}

await updateEvent(event);

const currentEvents = get().events;
set({ events: [...currentEvents, event] });

console.info(`Donation event ${event.eventId} created successfully.`);
} catch (error) {
console.error('Error adding donation event:', error);
throw new Error('Failed to create donation event.');
}
)
);
},
}));

export default useEventStore;
107 changes: 48 additions & 59 deletions src/stores/organizationStore.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { create } from 'zustand';
import { createJSONStorage, persist } from 'zustand/middleware';
import { collection, onSnapshot, getDocs } from 'firebase/firestore';

import { db } from '@/utils/firebase';
Expand All @@ -12,72 +11,62 @@ interface OrganizationState {
subscribeToProfiles: () => void;
}

const useOrganizationStore = create<OrganizationState>()(
persist(
(set) => ({
organizationProfiles: [],
loading: true,
error: null,
const useOrganizationStore = create<OrganizationState>()((set) => ({
organizationProfiles: [],
loading: true,
error: null,

fetchProfiles: async () => {
try {
set({ loading: true });
const organizationsCollection = collection(db, 'organization');
const snapshot = await getDocs(organizationsCollection);
fetchProfiles: async () => {
try {
set({ loading: true });
const organizationsCollection = collection(db, 'organization');
const snapshot = await getDocs(organizationsCollection);

if (snapshot.empty) {
console.info('No organization profiles found.');
set({ organizationProfiles: [], loading: false });
return;
}
if (snapshot.empty) {
console.info('No organization profiles found.');
set({ organizationProfiles: [], loading: false });
return;
}

const profiles: OrganizationProfile[] = snapshot.docs.map((doc) => ({
...doc.data(),
uid: doc.id,
})) as OrganizationProfile[];
const profiles: OrganizationProfile[] = snapshot.docs.map((doc) => ({
...doc.data(),
uid: doc.id,
})) as OrganizationProfile[];

set({ organizationProfiles: profiles, loading: false });
} catch (error) {
console.error('Error fetching organization profiles:', error);
set({ error: (error as Error).message, loading: false });
}
},

subscribeToProfiles: () => {
const organizationsCollection = collection(db, 'organization');
set({ organizationProfiles: profiles, loading: false });
} catch (error) {
console.error('Error fetching organization profiles:', error);
set({ error: (error as Error).message, loading: false });
}
},

const unsubscribe = onSnapshot(
organizationsCollection,
(snapshot) => {
if (snapshot.empty) {
console.info('No organization profiles found.');
set({ organizationProfiles: [], loading: false });
return;
}
subscribeToProfiles: () => {
const organizationsCollection = collection(db, 'organization');

const profiles: OrganizationProfile[] = snapshot.docs.map(
(doc) => ({
...doc.data(),
uid: doc.id,
})
) as OrganizationProfile[];
const unsubscribe = onSnapshot(
organizationsCollection,
(snapshot) => {
if (snapshot.empty) {
console.info('No organization profiles found.');
set({ organizationProfiles: [], loading: false });
return;
}

set({ organizationProfiles: profiles, loading: false });
},
(error) => {
console.error('Error subscribing to organization profiles:', error);
set({ error: error.message, loading: false });
}
);
const profiles: OrganizationProfile[] = snapshot.docs.map((doc) => ({
...doc.data(),
uid: doc.id,
})) as OrganizationProfile[];

return unsubscribe;
set({ organizationProfiles: profiles, loading: false });
},
}),
{
name: 'organization-store',
storage: createJSONStorage(() => sessionStorage),
}
)
);
(error) => {
console.error('Error subscribing to organization profiles:', error);
set({ error: error.message, loading: false });
}
);

return unsubscribe;
},
}));

export default useOrganizationStore;
7 changes: 7 additions & 0 deletions src/stores/userStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ const useUserStore = create<UserState>()(
},

login: async (userType, navigate) => {
const fetchEventsByIds = useEventStore.getState().fetchEventsByIds;

try {
set({ loading: true });
const profile = await loginUser(navigate, userType);
Expand All @@ -61,6 +63,10 @@ const useUserStore = create<UserState>()(
user: { ...profile, role: userType },
error: null,
});
const currentUser = get().user;
if (currentUser && currentUser.joinedEvents?.length > 0) {
await fetchEventsByIds(currentUser.joinedEvents);
}
}
} catch (error) {
console.error('Error during login:', error);
Expand All @@ -76,6 +82,7 @@ const useUserStore = create<UserState>()(
await logoutUser(navigate);

set({ user: undefined, error: null });
useEventStore.getState().setEvents([]);
} catch (error) {
console.error('Error during logout:', error);
set({ error: 'Logout failed. Please try again.' });
Expand Down

0 comments on commit 44ba14f

Please sign in to comment.