Created
April 4, 2023 16:30
-
-
Save sina-salahshour/b0b14e64791f0929cbeb5092a15e0c59 to your computer and use it in GitHub Desktop.
next 13 useQueryValue
This file contains hidden or 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 { usePathname, useRouter, useSearchParams } from "next/navigation"; | |
| interface QueryValueOptions<T> { | |
| serializer: (value: T) => string; | |
| deserializer: (value: string) => T; | |
| } | |
| type UseQueryReturn<T> = [value: T[], setValue: (value: T[]) => void]; | |
| const defaultSerializer = (value: any) => String(value); | |
| const defaultDeserializer = (value: string) => String(value); | |
| export function useQueryValue( | |
| key: string | |
| ): [value: string[] | undefined, setValue: (value: string[]) => void]; | |
| export function useQueryValue( | |
| key: string, | |
| defaultValue: string[] | |
| ): UseQueryReturn<string>; | |
| export function useQueryValue<T>( | |
| key: string, | |
| defaultValue: T[], | |
| options: QueryValueOptions<T> | |
| ): UseQueryReturn<T>; | |
| export function useQueryValue<T>( | |
| key: string, | |
| defaultValue?: T[], | |
| options?: QueryValueOptions<T> | |
| ) { | |
| const searchParams = useSearchParams(); | |
| const pathname = usePathname(); | |
| const { replace } = useRouter(); | |
| const { serializer, deserializer } = { | |
| serializer: defaultSerializer, | |
| deserializer: defaultDeserializer, | |
| ...options, | |
| }; | |
| const rawValue = searchParams.getAll(key); | |
| const isValueProvided = rawValue.length !== 0; | |
| const value = isValueProvided | |
| ? rawValue.map((item) => deserializer(item)) | |
| : defaultValue; | |
| const setValue = (value: T[]) => { | |
| const params = new URLSearchParams( | |
| Array.from(searchParams.entries()).filter((item) => item[0] !== key) | |
| ); | |
| value.forEach((item) => params.append(key, serializer(item))); | |
| replace(`${pathname}?${params}`); | |
| }; | |
| return [value, setValue]; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment