From b2d7623df11424bbdc16b20ce9aa1faa1e42941c Mon Sep 17 00:00:00 2001 From: SWARVY Date: Thu, 8 Aug 2024 15:24:29 +0900 Subject: [PATCH] feat(time): add useTimeTableParams for managing time table search parameters (#97) --- .../model/hooks/useTimeTableParams.ts | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 apps/time/src/widgets/time-table/model/hooks/useTimeTableParams.ts diff --git a/apps/time/src/widgets/time-table/model/hooks/useTimeTableParams.ts b/apps/time/src/widgets/time-table/model/hooks/useTimeTableParams.ts new file mode 100644 index 00000000..459909bf --- /dev/null +++ b/apps/time/src/widgets/time-table/model/hooks/useTimeTableParams.ts @@ -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('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 }; +}