Skip to content

Commit

Permalink
feat(time): add useTimeTableParams for managing time table search par…
Browse files Browse the repository at this point in the history
…ameters (#97)
  • Loading branch information
SWARVY committed Aug 8, 2024
1 parent 4df7d1d commit b2d7623
Showing 1 changed file with 61 additions and 0 deletions.
61 changes: 61 additions & 0 deletions apps/time/src/widgets/time-table/model/hooks/useTimeTableParams.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
'use client';

import { useEffect, useMemo, useState } from 'react';

import { useClientSearchParams } from '@/shared/lib';
import { DayStatus } from '@/widgets/time-table';
import { useRouter } from 'next/navigation';

export interface SearchParamsActionType {
get: (key: string) => string | null;
getParams: () => string;
set: (key: string, value: string) => void;
append: (key: string, value: string) => void;
remove: (key: string) => void;
}

export default function useTimeTableParams(): {
dayStatus: DayStatus;
searchParams: URLSearchParams;
searchParamsAction: SearchParamsActionType;
} {
const [dayStatus, setDayStatus] = useState<DayStatus>('day');
const searchParams = useClientSearchParams();
const router = useRouter();

const searchParamsAction = useMemo(
() => ({
get: (key: string) => {
return searchParams.get(key);
},
getParams: () => {
return searchParams.toString();
},
set: (key: string, value: string) => {
searchParams.set(key, value);
router.push(`/timetable?${searchParamsAction.getParams()}`);
},
append: (key: string, value: string) => {
searchParams.append(key, value);
router.push(`/timetable?${searchParamsAction.getParams()}`);
},
remove: (key: string) => {
searchParams.delete(key);
router.push(`/timetable?${searchParamsAction.getParams()}`);
},
}),
[searchParams, router],
);

useEffect(() => {
const currentDayStatus = searchParamsAction.get('classType');

if (currentDayStatus !== dayStatus || !currentDayStatus) {
searchParamsAction.set('classType', currentDayStatus ?? 'day');
setDayStatus((currentDayStatus as DayStatus) ?? 'day');
router.push(`/timetable?${searchParamsAction.getParams()}`);
}
}, [searchParams, setDayStatus, router]);

return { dayStatus, searchParams, searchParamsAction };
}

0 comments on commit b2d7623

Please sign in to comment.