|
import { usePathname, useSearchParams } from 'next/navigation' |
|
import { useState } from 'react' |
|
|
|
type UseTabSearchParamsOptions = { |
|
defaultTab: string |
|
routingBehavior?: 'push' | 'replace' |
|
searchParamName?: string |
|
disableSearchParams?: boolean |
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export const useTabSearchParams = ({ |
|
defaultTab, |
|
routingBehavior = 'push', |
|
searchParamName = 'category', |
|
disableSearchParams = false, |
|
}: UseTabSearchParamsOptions) => { |
|
const pathName = usePathname() |
|
const searchParams = useSearchParams() |
|
const [activeTab, setTab] = useState<string>( |
|
!disableSearchParams |
|
? (searchParams.get(searchParamName) || defaultTab) |
|
: defaultTab, |
|
) |
|
|
|
const setActiveTab = (newActiveTab: string) => { |
|
setTab(newActiveTab) |
|
if (disableSearchParams) |
|
return |
|
history[`${routingBehavior}State`](null, '', `${pathName}?${searchParamName}=${newActiveTab}`) |
|
} |
|
|
|
return [activeTab, setActiveTab] as const |
|
} |
|
|