Last active
April 20, 2023 11:00
-
-
Save ValentaTomas/e34ae63666f237c097a4108151b34a91 to your computer and use it in GitHub Desktop.
Save and retrieve page tab information with query string in Next.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useRouter } from 'next/router' | |
import { useCallback } from 'react' | |
type Base = Record<string, string | number> | |
interface SetTab<T> { | |
(tab: keyof T): void | |
} | |
function compareTabsCaseInsensitive<T extends Base>(tabs: T, tab?: string) { | |
return Object | |
.values(tabs) | |
.find(v => v.toString().toLowerCase() === tab?.toLowerCase()) | |
} | |
export function useQueryTab<T extends Base>(key: string, tabs: T, defaultTab: keyof T): [keyof T, SetTab<T>] { | |
const router = useRouter() | |
const tab = compareTabsCaseInsensitive(tabs, router.query[key] as string) as keyof T || defaultTab | |
const setTab = useCallback<SetTab<T>>(tab => { | |
router.push({ | |
pathname: router.pathname, | |
query: { | |
...router.query, | |
[key]: tabs[tab] as string, | |
} | |
}, undefined, { shallow: true }) | |
}, [key, router, tabs]) | |
return [tab, setTab] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment